In Python, exceptions are events that occur during the execution of a program that disrupt its normal
flow. These events usually indicate that an error has occurred, such as invalid input, division by zero,
or accessing a non-existent file.
Python provides a robust mechanism to handle these errors gracefully through the use of exceptions,
which allows developers to manage errors without crashing the program.
1 What is an Exception?
An exception is an error detected during execution. It is represented by an exception object in
Python.
2. Common Exceptions
Python includes built-in exceptions such as:
ValueError: Raised when an operation or function receives an argument of the correct type
but inappropriate value.
TypeError: Raised when an operation is applied to an object of inappropriate type.
ZeroDivisionError: Raised when dividing by zero.
FileNotFoundError: Raised when a file or directory is requested but does not exist.
IndexError: Raised when accessing a list index out of range.
3. Handling Exceptions
To handle exceptions, Python uses a try-except block. This prevents the program from crashing and
allows for alternative actions to be taken.
Example:
try:
number = int(input("Enter a number: "))
result = 10 / number
print("Result:", result)
except ZeroDivisionError:
print("You cannot divide by zero!")
except ValueError:
print("Please enter a valid integer!")
Explanation:
1. Purpose: This program demonstrates how to handle multiple exceptions in Python.
2. Details:
o The try block contains code that might raise an exception.
o int(input(...)): If the user enters a non-numeric value, it raises a ValueError.
o 10 / number: If the user enters 0, it raises a ZeroDivisionError.
o If either exception occurs, the appropriate except block handles it.
3. Example Run:
o Input: 0
Output: You cannot divide by zero!
o Input: abc
Output: Please enter a valid integer!
The else Clause
The else block executes if no exception is raised.
try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print("Division successful:", result)
Explanation:
1. Purpose: This program shows the use of the else clause.
2. Details:
o The try block executes successfully because 10 / 2 does not raise an exception.
o The else block runs if no exception is raised.
o If a ZeroDivisionError had occurred, the else block would not execute.
3. Example Run:
o Output: Division successful: 5.0
The finally Clause
The finally block is always executed, regardless of whether an exception occurs or not. It is
typically used for cleanup tasks.
try:
file = open("example.txt", "r")
print(file.read())
except FileNotFoundError:
print("File not found!")
finally:
print("Execution completed.")
Explanation:
1. Purpose: This program demonstrates the finally clause, which executes no matter what
happens.
2. Details:
o The try block attempts to open and read a file named example.txt.
o If the file does not exist, a FileNotFoundError is raised and handled by the except
block.
o The finally block runs regardless of whether an exception occurred. It is often used
for cleanup (e.g., closing files).
3. Example Run:
o If the file exists:
Output: The file content is displayed, followed by Execution completed.
o If the file does not exist:
Raising Exceptions
we can raise exceptions manually using the raise keyword.
age = -1
if age < 0:
raise ValueError("Age cannot be negative!")
Explanation:
1. Purpose: This program demonstrates how to manually raise an exception.
2. Details:
o If the variable age is negative, the raise keyword is used to throw a ValueError with a
custom error message.
o This stops the program unless the exception is caught elsewhere.
3. Example Run:
o Output: ValueError: Age cannot be negative!
Custom Exceptions
Python allows you to define custom exceptions by creating a new exception class that inherits from
the Exception base class.
class CustomError(Exception):
pass
try:
raise CustomError("This is a custom error!")
except CustomError as e:
print(e)
Explanation:
1. Purpose: This program demonstrates how to create and use custom exceptions.
2. Details:
o A new exception class CustomError is created by inheriting from the Exception base
class.
o The try block explicitly raises a CustomError with a custom message.
o The except block catches this specific exception and prints its message.
3. Example Run:
o Output: This is a custom error!
Summary
Exceptions allow programs to respond gracefully to errors.
The try-except block is used to handle exceptions.
Use else for code that should execute only if no exceptions occur.
Use finally for cleanup actions that must always be executed.
Custom exceptions can make your error handling more specific and meaningful.