Python Exception Handling Tutorial (2026): Try, Except, Else, Finally
Python Exception Handling Tutorial
What is Exception Handling in Python?
Exception Handling is a feature in Python that helps a
program deal with unexpected errors while it is running. Instead of stopping
the program immediately when an error occurs, Python allows you to catch the
error, display a meaningful message, and decide what should happen next.
Think about a calculator application. If someone tries to
divide a number by zero, the application should not suddenly close. A better
approach is to display a message like "Division by zero is not
allowed." This is exactly what exception handling is designed to do.
Exception handling makes programs more reliable because
it allows developers to anticipate possible problems and respond to them
gracefully. It is widely used in file handling, database connections, user
input validation, web applications, and many other real-world programs.
Example
try:
number = 10 / 0
except ZeroDivisionError:
print("You
cannot divide by zero.")
Output
You cannot divide by zero.
Why Exception Handling Matters
- Prevents programs from crashing unexpectedly.
- Provides clear and user-friendly error messages.
- Improves the reliability of applications.
- Makes debugging and maintenance easier.
- Helps create professional software that can handle invalid input or unexpected situations.
·
The try statement is the starting point of exception handling
in Python. It is used to write code that may generate an error while the
program is running. Instead of allowing the program to stop suddenly, Python
first checks the code inside the try block. If everything runs successfully, the program continues normally.
If an error occurs, Python immediately stops executing the remaining statements
inside the try block and
searches for a matching except block to
handle the error.
·
Think of the try block as a safety zone where you place risky code such as user input,
mathematical calculations, file operations, or database connections. These
operations may fail because of unexpected situations, so they should be
protected with a try block.
yntax
try:
# Code that may
generate an exception
Example
try:
number =
int(input("Enter a number: "))
result = 100 /
number
print("Result:", result)
If the user enters 10, the program runs successfully.
If the user enters 0, Python raises a
ZeroDivisionError, and the program looks for an except block.
Why is the try Block Important?
- Protects code that may produce runtime errors.
- Prevents the program from terminating unexpectedly.
- Makes applications more reliable.
- Provides the foundation for exception handling.
t
·
What is the except Statement in Python?
·
The except statement is used to catch and handle exceptions that
occur inside the try block.
When an exception is raised, Python skips the remaining code in the try block and executes the matching except block. This allows the program to display a meaningful message or
perform another action instead of crashing.
·
You can catch a specific exception such as ValueError or ZeroDivisionError, or you can catch multiple exceptions separately.
· Syntax
·
try:
·
#
Risky code
·
except ExceptionType:
·
#
Code to handle the exception
· Example
·
try:
·
number = int(input("Enter a number:
"))
·
print(100 / number)
·
·
except ZeroDivisionError:
·
print("Division by zero is not
allowed.")
·
·
except ValueError:
·
print("Please enter a valid
number.")
·
Output
·
Input
·
0
·
Output
·
Division by zero is not allowed.
Advantages of Using except
- Prevents sudden program termination.
- Displays user-friendly error messages.
- Allows different errors to be handled separately.
- Improves the user experience.
p
What is the else Block in Python?
The else block is an optional part of exception
handling. It runs only when no exception occurs inside the try block. If
an error is raised, the else block is skipped completely.
The else block is useful for writing code that should
execute only after the try block completes successfully. This keeps your
program organized because the risky code remains inside the try block, while
the success-related code stays in the else block.
Syntax
try:
# Risky code
except:
# Error handling
else:
# Executes only if
no exception occurs
Example
try:
number =
int(input("Enter a number: "))
except ValueError:
print("Invalid input.")
else:
print("Square
=", number * number)
Output (Valid Input)
Enter a number:
5
Square = 25
Output (Invalid Input)
Enter a number:
abc
Invalid input.
Notice that the else block does not execute because an
exception occurred.
Why Use the else Block?
- Separates successful code from error-handling code.
- Makes programs easier to understand.
- Improves code readability.
- Prevents unnecessary nesting of statements.
What is the finally Block in Python?
The finally block is another optional part of
exception handling. The code inside the finally block always executes,
regardless of whether an exception occurs or not.
Even if the program encounters an error, the finally block
still runs before the program ends. This makes it ideal for cleanup tasks such
as closing files, disconnecting databases, releasing memory, or closing network
connections.
Syntax
try:
# Risky code
except:
# Error handling
finally:
# Always executes
Example
try:
print(100 / 0)
except ZeroDivisionError:
print("Cannot
divide by zero.")
finally:
print("Program execution completed.")
Output
Cannot divide by zero.
Program execution completed.
Example Without an Exception
try:
print("Welcome")
finally:
print("Thank
you")
Output
Welcome
Thank you
Why Use the finally Block?
- Ensures cleanup code always runs.
- Prevents resource leaks.
- Closes files and database connections properly.
- Makes applications more reliable.
Real-Life Example
Imagine borrowing a library book.
Whether you finish reading it or not, you must return the
book to the library.
Returning the book is similar to the finally block because
it happens in every situation.
What is the raise Statement in Python?
The raise statement is used to generate an exception
manually. Normally, Python raises exceptions automatically when an error
occurs. However, sometimes developers want to create their own rules. In such
cases, the raise keyword is used.
For example, a banking application may not allow withdrawals
greater than the available balance. Even though Python does not consider this a
built-in error, the programmer can raise an exception to stop the transaction.
Syntax
raise ExceptionType("Error Message")
Example
age = 16
if age < 18:
raise
Exception("Age must be 18 or above.")
print("Eligible")
Output
Exception: Age must be 18 or above.
Why Use raise?
- Validates user input.
- Enforces business rules.
- Stops invalid operations immediately.
- Makes errors easier to understand.
What are Custom Exceptions in Python?
A Custom Exception is a user-defined exception
created by the programmer. Python provides many built-in exceptions, but in
real-world applications they may not describe every type of error. By creating
a custom exception, you can give meaningful names to application-specific
problems.
Custom exceptions are created by defining a new class that
inherits from Python's built-in Exception class.
Syntax
class ExceptionName(Exception):
pass
Example 1: Age Validation
class InvalidAgeError(Exception):
pass
age = 15
if age < 18:
raise
InvalidAgeError("Age must be 18 or above.")
Output
InvalidAgeError: Age must be 18 or above.
Example 2: Bank Balance
class LowBalanceError(Exception):
pass
balance = 500
withdraw = 1000
if withdraw > balance:
raise
LowBalanceError("Insufficient balance.")
Output
LowBalanceError: Insufficient balance.
Why Use Custom Exceptions?
- Makes error messages meaningful.
- Represents business-specific problems clearly.
- Improves debugging.
- Makes code easier to maintain.
- Helps large projects organize error handling.
Business Rules:
- Minimum order amount: ₹500
- Maximum quantity: 10 items
- Coupon expires after a specific date
Instead of showing a generic error, you can create custom
exceptions such as:
- MinimumOrderError
- InvalidCouponError
- QuantityLimitError
These names clearly explain what went wrong, making the
application easier to understand for both users and developers.
Summary
Python exception handling makes programs more reliable by
managing unexpected runtime errors gracefully.
- try contains code that might produce an error.
- except catches and handles exceptions.
- else executes only when no exception occurs.
- finally always runs and is mainly used for cleanup tasks.
- raise allows you to generate exceptions manually based on your own rules.
- Custom Exceptions let you define meaningful, application-specific error types that improve code readability and maintenance.
Comments
Post a Comment