Python Exception Handling¶
Exception Handling: Dealing with Errors¶
In programming, an Exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. Essentially, it's a "crash" or an "error."
Why handle Exceptions?¶
- Prevent Crashing: If an error occurs (like dividing by zero), you don't want the whole program to just stop.
- User Experience: Instead of a cryptic computer error, you can show a friendly message (e.g., "Please enter a valid number").
- Cleanup: Ensure that things like files or database connections are closed even if an error occurs.
The "Try-Catch" Logic¶
- Try: "Try running this code."
- Catch/Except: "If an error happens, do this instead."
- Finally: "No matter what happens, always do this at the end."
Logic First
Exception handling is about defensive programming. You are anticipating what could go wrong and providing a safety net.
Try ... Except¶
The try block lets you test a block of code for errors. The except block lets you handle the error.
Since the variable x is not defined, the program will jump to the except block instead of crashing.
The else Keyword¶
You can use the else keyword to define a block of code to be executed if no errors were raised: