Python Exception Handling Complete Guide
Learn Python exception handling - try-except blocks, finally clause, custom exceptions with practical examples, patterns, and real-world applications for robust error management.
try-except
Catch and handle errors
Custom Exceptions
Create your own error types
finally Clause
Cleanup operations
raise Statement
Throw exceptions
What is an Exception?
An exception is an error that occurs during program execution.
print(10 / 0)
Output: ZeroDivisionError: division by zero
Without exception handling, the program crashes.
try → success or except → optional else / finally for cleanup.Why Use Exception Handling?
- Prevent program crashes
- Display user-friendly error messages
- Handle unexpected situations
- Improve program reliability
Basic Syntax
try:
# risky code
except:
# code to handle error
try:
num = 10 / 0
except:
print("Error occurred")
Output: Error occurred
Flow of Exception Handling
1. try and except
The try block contains code that may produce an error. The except block handles the error.
try:
a = int(input("Enter number: "))
print(100 / a)
except:
print("Invalid input")
Handling Specific Exceptions
try:
num = int(input("Enter number: "))
result = 10 / num
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Please enter valid integer")
Common Python Exceptions
| Exception | Description |
|---|---|
| ZeroDivisionError | Division by zero |
| ValueError | Invalid value |
| TypeError | Wrong data type |
| IndexError | Invalid list index |
| KeyError | Invalid dictionary key |
| NameError | Variable not defined |
| FileNotFoundError | File does not exist |
Multiple Exceptions in One Block
try:
x = int(input())
print(10 / x)
except (ValueError, ZeroDivisionError):
print("Error occurred")
Using else Block
try:
num = int(input("Enter number: "))
print(10 / num)
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("Program executed successfully")
Using finally Block
try:
file = open("data.txt")
except FileNotFoundError:
print("File not found")
finally:
print("Execution completed")
try-except-else-finally Structure
try:
num = int(input())
except ValueError:
print("Invalid input")
else:
print("No exception")
finally:
print("Always executed")
Raising and Custom Exceptions
Raising Exceptions
age = -5
if age < 0:
raise ValueError("Age cannot be negative")
Custom Exceptions
class InvalidAgeError(Exception):
pass
age = -1
if age < 0:
raise InvalidAgeError("Invalid age")
Using Exception Object
try:
print(10 / 0)
except ZeroDivisionError as e:
print("Error:", e)
Output: Error: division by zero
Nested try-except
try:
try:
print(10 / 0)
except ZeroDivisionError:
print("Inner exception handled")
except:
print("Outer exception handled")
File Handling with Exceptions
try:
file = open("sample.txt", "r")
print(file.read())
except FileNotFoundError:
print("File does not exist")
finally:
print("File operation completed")
Best Practices
- Catch specific exceptions instead of generic except
- Use finally for cleanup tasks
- Avoid hiding errors unnecessarily
- Write meaningful error messages
- Use custom exceptions for large projects
Real-Life Examples
balance = 5000
try:
amount = int(input("Enter withdrawal amount: "))
if amount > balance:
raise ValueError("Insufficient balance")
print("Withdrawal successful")
except ValueError as e:
print(e)
try:
data = [10, 20, 30]
print(data[5])
except IndexError:
print("Index out of range")
Interview Questions
1. Difference between Error and Exception?
Errors are serious issues. Exceptions can be handled.
2. Difference between except and finally?except runs only when exception occurs. finally always runs.
3. Why use custom exceptions?
For better readability and project-specific error handling.
4. Can finally run without except?
Yes.
try:
print("Hello")
finally:
print("Done")
Mini Practice Programs
- Handle divide by zero
- Handle invalid user input
- Handle file not found
- Create custom exception
- Handle list index error
Summary
try-> risky codeexcept-> handles errorselse-> runs if no errorfinally-> always runsraise-> manually create exceptions- Custom exceptions improve program structure