Topic 15: Exception Handling (Try-Except)
In programming, errors are inevitable. A file might be missing, or a user might try to divide by zero. In C, these often lead to "Segmentation Faults" or crashes. In Python, we use Exceptions to catch these errors gracefully so the program can keep running.
1. The Try-Except Block
The logic is simple: "Try" to run a piece of code. If an "Except"-ion (error) occurs, jump to a backup plan instead of crashing.
try: The block of code you want to test for errors.except: The block that handles the error.else: (Optional) Runs if no errors occurred.finally: (Optional) Runs no matter what (often used for cleanup, like closing a file).
2. Common Exception Types
Python has many built-in exceptions. You can catch specific ones or use a general one:
ZeroDivisionError: Dividing by zero.ValueError: Passing a value of the right type but wrong content (e.g.,int("abc")).FileNotFoundError: Trying to open a file that doesn't exist.TypeError: Doing something mathematically impossible (e.g., adding a string to an integer).
try:
number = int(input("Enter a number to divide 100 by: "))
result = 100 / number
except ZeroDivisionError:
print("Error: You cannot divide by zero!")
except ValueError:
print("Error: Please enter a valid whole number.")
except Exception as e:
# This catches any other unexpected errors
print(f"An unexpected error occurred: {e}")
else:
print(f"Success! The result is {result}")
finally:
print("Execution complete. (This always runs)")3. Raising Exceptions
You can also intentionally trigger an error using the raise keyword if a condition in your code isn't met.
age = -5
if age < 0:
raise ValueError("Age cannot be negative!")