Python Exception Handling Tutorial | Try, Except, Else & Finally with Examples
No matter how well a program is written, unexpected errors can occur during execution. A user may enter invalid input, a required file might not exist, a database connection could fail, or a network request may time out. If these situations are not handled properly, the program may terminate unexpectedly and provide a poor user experience.
Python provides Exception Handling, a powerful mechanism that allows developers to detect runtime errors and respond to them gracefully without crashing the application.
In this lesson, you’ll learn how to use try, except, else, and finally blocks, handle different types of exceptions, raise your own exceptions, create custom exceptions, and implement professional error handling techniques used in real-world software development.
By the end of this lesson, you’ll be able to build reliable Python applications that can recover from unexpected situations and provide meaningful error messages to users.
Learning Objectives
After completing this lesson, you will be able to:
- Understand exceptions and runtime errors.
- Differentiate between syntax errors and exceptions.
- Use
tryandexceptblocks. - Handle multiple exceptions.
- Use
elseandfinally. - Raise exceptions using
raise. - Create custom exceptions.
- Apply exception handling in real-world applications.
- Follow best practices for robust code.
Topics Covered
- Introduction to Exception Handling
- Types of Errors
- try Block
- except Block
- Multiple Exceptions
- else Block
- finally Block
- Raising Exceptions
- Custom Exceptions
- Best Practices
Detailed Lesson Content
Introduction to Exception Handling
Imagine you’re using an Online Banking Application.
You enter:
- Account Number ✔
- Amount ✔
But accidentally type letters instead of numbers.
Without exception handling:
❌ The application crashes.
With exception handling:
✔ The application displays:
“Invalid amount. Please enter a valid number.”
The program continues running without crashing.
This is the purpose of Exception Handling.
Exception handling allows developers to anticipate possible errors and handle them gracefully.
What is an Exception?
An Exception is a runtime error that interrupts the normal execution of a program.
Examples include:
- Division by zero
- Invalid user input
- File not found
- Network timeout
- Database connection failure
- Index out of range
Syntax Error vs Runtime Error
Syntax Error
Occurs before the program starts.
Example
if True
print("Hello")
Output
SyntaxError
Runtime Error (Exception)
Occurs while the program is running.
print(10/0)
Output
ZeroDivisionError
The try Block
Code that may generate an exception is placed inside a try block.
Syntax
try:
# Risky Code
Example
try:
number = int(input("Enter Number: "))
print(number)
If an error occurs, Python immediately looks for an except block.
The except Block
The except block handles the exception.
Example
try:
number = int(input("Enter Number: "))
print(number)
except:
print("Invalid Input")
Output
Enter Number: abc
Invalid Input
Instead of crashing, the program displays a friendly message.
Handling Specific Exceptions
Professional developers handle specific exceptions.
Example
try:
result = 20/0
except ZeroDivisionError:
print("Cannot divide by zero.")
Output
Cannot divide by zero.
Multiple Exceptions
A program may produce different types of errors.
try:
number = int(input("Enter Number: "))
result = 100/number
except ValueError:
print("Please enter numbers only.")
except ZeroDivisionError:
print("Division by zero is not allowed.")
Catching Multiple Exceptions Together
try:
number = int(input())
except (ValueError, TypeError):
print("Invalid Input")
Using Exception as a Variable
You can access the actual error message.
try:
number = int(input())
except Exception as error:
print(error)
Example Output
invalid literal for int()
Useful for debugging applications.
The else Block
The else block executes only if no exception occurs.
Example
try:
number = int(input("Enter Number: "))
except ValueError:
print("Invalid Number")
else:
print("Square =",number**2)
If the input is valid, the else block runs.
The finally Block
The finally block always executes whether an exception occurs or not.
Example
try:
file = open("student.txt")
except FileNotFoundError:
print("File Not Found")
finally:
print("Program Finished")
Output
File Not Found
Program Finished
This is commonly used for:
- Closing database connections
- Closing files
- Releasing resources
- Cleaning temporary data
Raising Exceptions
Developers can generate their own exceptions using raise.
Example
age = 15
if age < 18:
raise Exception("Age must be at least 18.")
Output
Exception: Age must be at least 18.
Custom Exceptions
Developers can create their own exception classes.
Example
class InvalidAgeError(Exception):
pass
age = 15
if age < 18:
raise InvalidAgeError("Invalid Age")
Custom exceptions improve code readability and make applications easier to maintain.
Common Built-in Exceptions
| Exception | Description |
|---|---|
| ValueError | Invalid value |
| TypeError | Wrong data type |
| ZeroDivisionError | Division by zero |
| IndexError | Invalid list index |
| KeyError | Missing dictionary key |
| FileNotFoundError | File not found |
| NameError | Variable not defined |
| AttributeError | Invalid object attribute |
Real-World Example 1: ATM Withdrawal
try:
balance = 5000
amount = int(input("Enter Amount: "))
if amount > balance:
raise Exception("Insufficient Balance")
print("Transaction Successful")
except Exception as error:
print(error)
Real-World Example 2: Student Marks
try:
marks = int(input("Enter Marks: "))
print("Marks:",marks)
except ValueError:
print("Please enter numeric marks.")
Real-World Example 3: File Handling
try:
file = open("students.txt")
print(file.read())
except FileNotFoundError:
print("Requested file does not exist.")
finally:
print("Closing Program")
Real-World Example 4: Login System
try:
username = input("Username: ")
password = input("Password: ")
if username != "admin" or password != "1234":
raise Exception("Invalid Credentials")
print("Login Successful")
except Exception as error:
print(error)
Common Mistakes
Using Bare except
Avoid this:
except:
print("Error")
Better:
except ValueError:
print("Invalid Number")
Ignoring Exceptions
Never leave an exception block empty.
Incorrect
except:
pass
Always log or display a meaningful message.
Catching Very General Exceptions
Handle specific exceptions whenever possible.
Best Practices
- Catch only expected exceptions.
- Avoid empty
exceptblocks. - Use
finallyto release resources. - Display meaningful error messages.
- Log exceptions in large applications.
- Create custom exceptions for business rules.
- Never hide critical errors silently.
Key Takeaways
- Exceptions occur during program execution.
trycontains risky code.excepthandles exceptions.elseexecutes when no exception occurs.finallyalways executes.raisegenerates custom exceptions.- Custom exception classes improve application design.
- Proper exception handling makes applications reliable and user-friendly.



