7.E Error Control: Try and except - JulTob/Python GitHub Wiki

๐Ÿ›ก๏ธ Error Control in Python โ€” try, except, finally, and raise

Programming is not just about making code work.
It is about making code robust when things go wrong.

Errors are inevitable:

  • A user enters text instead of a number โŒ
  • A file does not exist ๐Ÿ“‚
  • A division by zero occurs โž—
  • A variable name is wrong ๐Ÿง 

Python provides a structured mechanism to detect, handle, and react to these situations: exceptions.

๐Ÿง  Exceptions

An exception is a signal that something unexpected happened during execution.

Instead of crashing immediately, Python allows you to:

  • Try to execute code
  • Catch problems if they occur
  • Decide what to do next

This is done with the try / except structure.

โš™๏ธ Basic Structure โ€” try and except

try:
    print("Try this")
except:
    print("Error Execution")

How it works

Python executes the try block.

If an error occurs:

  • Execution stops inside try
  • Control jumps to except
  • Program continues afterward.
    • Optional:
      • else only runs when no error happened
        • Good to ensure you received a value or set an important parameter, or use a substitute
      • finally:
        • Runs anyway.

โš ๏ธ Important: A bare except: catches everything, which is usually not recommended in professional code.

๐ŸŽฏ Handling Specific Errors

You can catch specific types of exceptions to react differently depending on the problem.

try:
    inpt = int(input("What? "))
    result = 12 / inpt

except ZeroDivisionError:
    print("Nope")

except ValueError:
    print("Uh?")

except (ImportError, NameError):
    print("How?")

except Exception as e:
    print("So... ";, e)



# ๐Ÿ“š Common Exception Types

Here are some of the most useful built-in exceptions:


Exception      | Meaning
-------------- | --
๐Ÿ“ฆ ImportError | Import failed
๐Ÿ“ IndexError  | List index out of range
๐Ÿท๏ธ NameError   | Variable not defined
๐Ÿงพ SyntaxError | Code cannot be parsed
๐Ÿ”ข TypeError   | Wrong data type
๐ŸŽฏ ValueError  | Correct type, wrong value
๐Ÿ—‚๏ธ IOError     | File issue
๐Ÿง  OSError     | System issue
๐Ÿ—๏ธ KeyError    | Dictionary key missing


# โœจ The `finally` Block โ€” Always Runs
Sometimes you need code that runs __no matter what happens__.
Typical use cases:
- Closing files
- Releasing resources
- Cleaning temporary state

````py
try:
    main()
except:
    correction()
finally:
    LastOne()

Guarantee

  • try โ†’ except (if needed) โ†’ finally (always)

Even if there is an error, finally executes.

๐Ÿš€ Raising Exceptions โ€” raise

You can trigger your own errors intentionally.

This is useful when detecting invalid states in your program.

print(1)
raise ValueError
print(2)   # never runs

With a message:

  • raise ImportError("Something happened")

๐Ÿ” Re-Raising Exceptions

Sometimes you want to:

  • Catch an error
  • Do something (log, print, cleanup)
  • Then propagate the error again
try:
    print(3 / 0)
except:
    print("Error happened")
    raise

This preserves the original traceback.

๐Ÿงฉ Mental Model โ€” Exception Pipeline

Think of exceptions like a signal traveling upward through the call stack.

Function A
   โ†“
Function B
   โ†“
Function C  โ† error occurs here โš ๏ธ
   โ†‘
Handled by nearest try/except

If nobody handles it โ†’ program crashes.


๐Ÿ’ก Best Practices

โœ… Catch specific exceptions whenever possible
โœ… Use finally for cleanup
โœ… Use raise for invalid program states
โœ… Provide informative messages
โŒ Avoid except: without specifying the error
โŒ Do not silently ignore exceptions (pass) unless justified


๐Ÿงช Practical Example โ€” Safe Division

def safe_division(a, b):
    try:
        return a / b
    except ZeroDivisionError:
        print("Division by zero is not allowed")
        return None

๐Ÿ Summary

Error control allows programs to be:

  • More reliable ๐Ÿ›ก๏ธ
  • More user-friendly ๐Ÿค
  • Easier to debug ๐Ÿ”
  • Safer in production ๐Ÿš€

Key tools:

  • try โ†’ attempt execution
  • except โ†’ handle problems
  • finally โ†’ always execute
  • raise โ†’ create exceptions

If you master exception handling, you move from writing scripts to writing robust software.

โš ๏ธ **GitHub.com Fallback** โš ๏ธ