An Exception is an error that happens during the execution of a program. When that error occurs, Python stops and generates an exception message.
Exception Handling is how you tell Python: "Hey, if this specific error happens, don't crash the program. Do this instead."
Basic Syntax
try:
# Code that might cause an error
except:
# Code to run if an error happens
1. Basic try...except
If you try to divide by zero, Python usually crashes. We can prevent that.
try:
result = 10 / 0
print(result)
except:
print("Error: You cannot divide by zero!")
Output:
Error: You cannot divide by zero!
2. Catching a Specific Exception
Best practice is to catch the exact error you expect.
try:
number = int("Hello") # This will cause a ValueError
except ValueError:
print("Error: Please enter a valid number.")
Output:
Error: Please enter a valid number.
3. Seeing the Error Message (as e)
You can store the actual error message inside a variable (commonly e).
try:
number = int("Hello")
except ValueError as e:
print("An error occurred:", e)
Output:
An error occurred: invalid literal for int() with base 10: 'Hello'
4. Multiple except Blocks
You can handle different errors in different ways.
try:
numbers = [10, 20, 30]
result = numbers[5] / 0 # This will cause an IndexError first
except ZeroDivisionError:
print("Divided by zero!")
except IndexError:
print("Index out of range! That item doesn't exist.")
Output:
Index out of range! That item doesn't exist.
5. Grouping Multiple Exceptions
You can handle multiple errors with a single block using a tuple.
try:
result = 10 / 0
except (ZeroDivisionError, ValueError):
print("Math or Value error happened.")
Output:
Math or Value error happened.
6. Catching ALL Exceptions (The Fallback)
If you don't know what error might happen, you can catch the base Exception class. (Use this sparingly, as it hides bugs).
try:
result = 10 / "apples"
except Exception as e:
print("Something went wrong:", e)
Output:
Something went wrong: unsupported operand type(s) for /: 'int' and 'str'
7. The else Block
The else block runs only if no exceptions were raised in the try block.
try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero.")
else:
print("Calculation successful! Result is", result)
Output:
Calculation successful! Result is 5.0
8. The finally Block
The finally block always runs, no matter what happens (error or no error). It is usually used for cleaning up (like closing files or database connections).
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero.")
finally:
print("This runs no matter what!")
Output:
Cannot divide by zero.
This runs no matter what!
9. Manually Triggering an Error (raise)
You can force an exception to happen using the raise keyword.
age = -5
try:
if age < 0:
raise ValueError("Age cannot be negative!")
print("Age is valid.")
except ValueError as e:
print("Caught an error:", e)
Output:
Caught an error: Age cannot be negative!
10. Handling KeyError (Dictionaries)
When you try to access a dictionary key that doesn't exist.
user = {"name": "Sita", "age": 25}
try:
print(user["email"])
except KeyError:
print("That key does not exist in the dictionary.")
Output:
That key does not exist in the dictionary.
11. Handling FileNotFoundError
When you try to open a file that isn't there.
try:
file = open("secret_passwords.txt", "r")
except FileNotFoundError:
print("File not found! Please check the filename.")
Output:
File not found! Please check the filename.
12. Handling TypeError
When an operation is applied to an object of the wrong type.
try:
total = 50 + "10"
except TypeError:
print("You cannot add an integer and a string together.")
Output:
You cannot add an integer and a string together.
13. The assert Keyword
assert tests a condition. If the condition is False, it raises an AssertionError. It's used mostly for testing and debugging.
price = 100
discount = 120
try:
assert discount <= price, "Discount cannot be greater than price!"
except AssertionError as e:
print("Assertion failed:", e)
Output:
Assertion failed: Discount cannot be greater than price!
14. Creating Custom Exceptions
You can create your own specific errors by inheriting from the Exception class.
class InsufficientFundsError(Exception):
pass
balance = 500
withdrawal = 1000
try:
if withdrawal > balance:
raise InsufficientFundsError("You don't have enough money.")
except InsufficientFundsError as e:
print("Transaction Failed:", e)
Output:
Transaction Failed: You don't have enough money.
15. Exception Handling in a Loop
This is common when asking a user for input until they provide something valid.
# Normally this would use input(), but we'll simulate it
user_inputs = ["abc", "xyz", "15"]
for item in user_inputs:
try:
age = int(item)
print(f"Success! Age is {age}")
break # Exit the loop once successful
except ValueError:
print(f"'{item}' is not a valid number. Trying next...")
Output:
'abc' is not a valid number. Trying next...
'xyz' is not a valid number. Trying next...
Success! Age is 15
Important Points to Remember
try: Put risky code here.except: Put error-handling code here.else: Code that runs ONLY if there were no errors.finally: Code that runs ALWAYS, used for cleanup.raise: Used to manually create/throw an error.- Never use a bare
except:if you can avoid it. Always try to catch specific errors likeexcept ValueError:so you don't accidentally hide unrelated bugs.