Exception
Exception
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?
2. Common Exceptions
ValueError: Raised when an operation or function receives an argument of the correct type
but inappropriate value.
FileNotFoundError: Raised when a file or directory is requested but does not exist.
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:
result = 10 / number
print("Result:", result)
except ZeroDivisionError:
except ValueError:
Explanation:
2. Details:
o The try block contains code that might raise an exception.
3. Example Run:
o Input: 0
o Input: abc
try:
result = 10 / 2
except ZeroDivisionError:
else:
Explanation:
2. Details:
o The try block executes successfully because 10 / 2 does not raise an exception.
3. Example Run:
The finally block is always executed, regardless of whether an exception occurs or not. It is
typically used for cleanup tasks.
try:
print(file.read())
except FileNotFoundError:
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:
Raising Exceptions
age = -1
if age < 0:
Explanation:
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:
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:
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 except block catches this specific exception and prints its message.
3. Example Run:
Summary
Use else for code that should execute only if no exceptions occur.
Custom exceptions can make your error handling more specific and meaningful.