7.E Error Control: Try and except - JulTob/Python GitHub Wiki
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.
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.
try:
print("Try this")
except:
print("Error Execution")Python executes the try block.
If an error occurs:
- Execution stops inside
try - Control jumps to
except - Program continues afterward.
- Optional:
-
elseonly runs when no error happened- Good to ensure you received a value or set an important parameter, or use a substitute
-
finally:- Runs anyway.
-
- Optional:
except: catches everything, which is usually not recommended in professional code.
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()-
try โ except (if needed) โ finally(always)
Even if there is an error, finally executes.
You can trigger your own errors intentionally.
This is useful when detecting invalid states in your program.
print(1)
raise ValueError
print(2) # never runsWith a message:
-
raiseImportError("Something happened")
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")
raiseThis preserves the original traceback.
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/exceptIf nobody handles it โ program crashes.
โ
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
def safe_division(a, b):
try:
return a / b
except ZeroDivisionError:
print("Division by zero is not allowed")
return NoneError 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.