Exception Handeling in Python
Exception Handeling in Python
What is an exception?
An exception in Python is an event that occurs
during the execution of a program that disrupts
the normal flow of the program's instructions.
When an error occurs within a Python program,
it raises an exception. If the exception is not
handled, the program will terminate and display
an error message.
Difference Between Exception and Error
# ZeroDivisionError (Exception)
n = 10
res = n / 0
Exception handling in Python is done using the try, except, else and finally
blocks.
try:
# Code that might raise an exception
except SomeException:
# Code to handle the exception
else:
# Code to run if no exception occurs
finally:
# Code to run regardless of whether an exception occurs
try, except, else and finally Blocks
• try Block: try block lets us test a block of code for errors. Python will
“try” to execute the code in this block. If an exception occurs, execution
will immediately jump to the except block.
• except Block: except block enables us to handle the error or exception.
If the code inside the try block throws an error, Python jumps to the
except block and executes it. We can handle specific exceptions or use a
general except to catch all exceptions.
• else Block: else block is optional and if included, must follow all except
blocks. The else block runs only if no exceptions are raised in the try
block. This is useful for code that should execute if the try block
succeeds.
• finally Block: finally block always runs, regardless of whether an
exception occurred or not. It is typically used for cleanup operations
(closing files, releasing resources).
Handling a Simple Exception in Python
Output
Not Valid!
Catching Multiple Exceptions
We can catch multiple exceptions in a single block if we need
to handle them in the same way or we can separate them if
different types of exceptions require different handling.
Output:
Error invalid literal for int() with base 10: 'twenty'
a = ["10", "twenty", 30] # Mixed list of integers and strings
try:
total = (a[0]) + (a[1]) # 'twenty' cannot be converted to int
except (ValueError, TypeError) as e:
print("Error", e)
except IndexError:
print("Index out of range.")
Output:
Error invalid literal for int() with base 10: 'twenty'
• Explanation:
• The ValueError is caught when trying to convert “twenty” to an
integer.
• TypeError might occur if the operation was incorrectly applied to
non-integer types, but it’s not triggered in this specific setup.
• IndexError would be caught if an index outside the range of the list
was accessed, but in this scenario, it’s under control.
Raise an Exception
We raise an exception in Python using the raise
keyword followed by an instance of the exception class
that we want to trigger. We can choose from built-in
exceptions or define our own custom exceptions by
inheriting from Python’s built-in Exception class.
Basic Syntax:
raise ExceptionType(“Error message”)
Example
def set(age):
if age < 0:
raise ValueError("Age cannot be negative.")
print(f"Age set to {age}")
try:
set(-5)
except ValueError as e:
print(e)
Output:
Age cannot be negative.
Explanation:
• The function set checks if the age is negative. If so, it raises a
ValueError with a message explaining the issue.
• This ensures that the age attribute cannot be set to an invalid
state, thus maintaining the integrity of the data.
Advantages of Exception Handling: