Exception Handling in Python
Exception handling is used to handle errors that occur while a Python program is running.
Without exception handling, an error can stop the entire program.
Python provides:
tryexceptelsefinallyraise
1. What is an Exception?
An exception is an error that occurs during program execution.
Example:
a = 10 b = 0 print(a / b)
Output:
ZeroDivisionError: division by zero
The program stops because Python cannot divide a number by zero.
2. try and except
The try block contains code that may produce an error.
The except block handles the error.
try: a = 10 b = 0 print(a / b) except: print("Something went wrong")
Output:
Something went wrong
Instead of crashing, the program handles the exception.
3. Handling a Specific Exception
It is better to specify the type of exception.
try: print(10 / 0) except ZeroDivisionError: print("Cannot divide by zero")
Output:
Cannot divide by zero
4. Common Exceptions
| Exception | Meaning |
|---|---|
ZeroDivisionError | Division by zero |
ValueError | Invalid value |
TypeError | Invalid data type operation |
NameError | Variable does not exist |
IndexError | Invalid list index |
KeyError | Dictionary key does not exist |
FileNotFoundError | File does not exist |
AttributeError | Invalid attribute or method |
ImportError | Import problem |
ModuleNotFoundError | Module cannot be found |
5. ValueError
Occurs when a function receives the correct type but an invalid value.
try: age = int("hello") except ValueError: print("Please enter a valid number")
Output:
Please enter a valid number
6. TypeError
Occurs when an operation is performed on incompatible types.
try: result = "10" + 5 except TypeError: print("Invalid data types")
Output:
Invalid data types
7. IndexError
Occurs when accessing an index that doesn't exist.
numbers = [10, 20, 30] try: print(numbers[5]) except IndexError: print("Index does not exist")
Output:
Index does not exist
8. KeyError
Occurs when a dictionary key doesn't exist.
student = { "name": "Ram", "age": 20 } try: print(student["city"]) except KeyError: print("Key not found")
Output:
Key not found
9. NameError
Occurs when a variable doesn't exist.
try: print(name) except NameError: print("Variable does not exist")
Output:
Variable does not exist
10. Multiple except Blocks
You can handle different exceptions separately.
try: a = int(input("Enter a number: ")) result = 10 / a print(result) except ValueError: print("Please enter a number") except ZeroDivisionError: print("Cannot divide by zero")
If the user enters:
abc
Output:
Please enter a number
If the user enters:
0
Output:
Cannot divide by zero
11. else
The else block executes when no exception occurs.
try: result = 10 / 2 except ZeroDivisionError: print("Cannot divide by zero") else: print("Result:", result)
Output:
Result: 5.0
Flow
try | Exception? / \ Yes No | | except else
12. finally
The finally block always executes, whether an exception occurs or not.
try: print(10 / 0) except ZeroDivisionError: print("Error occurred") finally: print("Program finished")
Output:
Error occurred Program finished
finally is commonly useful for cleanup operations such as closing files or connections.
13. Complete try-except-else-finally
try: number = int(input("Enter a number: ")) result = 100 / number except ValueError: print("Invalid number") except ZeroDivisionError: print("Cannot divide by zero") else: print("Result:", result) finally: print("Execution completed")
14. Getting the Error Message
You can store the exception using as.
try: print(10 / 0) except ZeroDivisionError as error: print("Error:", error)
Output:
Error: division by zero
15. Catching Multiple Exceptions
You can handle multiple exception types in one except.
try: number = int(input("Enter number: ")) print(10 / number) except (ValueError, ZeroDivisionError): print("Invalid input")
16. raise
The raise statement is used to manually create an exception.
age = 15 if age < 18: raise ValueError("Age must be 18 or above")
Output:
ValueError: Age must be 18 or above
17. Using raise with try-except
try: age = 15 if age < 18: raise ValueError("You must be 18 or older") except ValueError as error: print(error)
Output:
You must be 18 or older
18. Custom Exception
You can create your own exception class.
class AgeError(Exception): pass
Then use it:
try: age = 15 if age < 18: raise AgeError("Age must be 18 or above") except AgeError as error: print(error)
Output:
Age must be 18 or above
19. Exception with File Handling
Exception handling is very useful when working with files.
try: with open("data.txt", "r") as file: print(file.read()) except FileNotFoundError: print("File not found")
If data.txt doesn't exist:
File not found
20. Exception with User Input
try: age = int(input("Enter your age: ")) print("Your age is:", age) except ValueError: print("Please enter a valid number")
If the user enters:
twenty
Output:
Please enter a valid number
21. try Cannot Be Used Alone
A try block must be followed by at least one of:
except else finally
Correct:
try: print("Hello") except: print("Error")
Incorrect:
try: print("Hello")
22. Difference Between Error and Exception
In beginner Python programming, these terms are often used together, but there is a useful distinction:
Syntax error
if x > 5 print(x)
Python cannot understand the syntax.
Exception
print(10 / 0)
The syntax is valid, but an error occurs during execution.
23. Best Practice
Avoid using a completely empty except when possible:
try: # code except: print("Error")
Instead, catch the specific exception:
try: number = int(input("Enter number: ")) except ValueError: print("Invalid number")
This makes your program easier to understand and debug.
Exception Handling Structure
try │ ├── Code that may cause an exception │ ├── except │ └── Handle the exception │ ├── else │ └── Runs if no exception occurs │ └── finally └── Always runs
Quick Summary
| Keyword | Purpose |
|---|---|
try | Code that may cause an exception |
except | Handles the exception |
else | Runs when no exception occurs |
finally | Always runs |
raise | Manually raises an exception |
Main idea: Exception handling allows your program to handle unexpected situations without suddenly crashing.