Python Exception Handling
Python Exception Handling is a core Python concept covering python Exception Handling: --8<-- "core-logic/exception-handling.md" This topic is essential for academic learning, board exam preparation, and developing optimized real-world code.
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."
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.
try:
print(x)
except:
print("An exception occurred")
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:
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
It's better to catch specific errors rather than a general except:.
try:
# code
except ZeroDivisionError:
print("You cannot divide by zero!")