PPL Experiment No-9
PPL Experiment No-9
Experiment No 9
Aim: To empower learners to write Python code by mastering error handling,
exception management.
Python Exception Handling handles errors that occur during the execution of a program.
Exception handling allows to respond to the error, instead of crashing the running program. It
enables you to catch and manage errors, making your code more robust and user-friendly.
Example: Trying to divide a number by zero will cause an exception.
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 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
Subject:
Year: FE Python Sem: II
Programming
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).
Python has many built-in exceptions, each representing a specific error condition. Some common
ones include:
Problem statement:-Basic Exception Handling*: Write a Python program that takes two
numbers as input and performs division. Implement exception handling to manage division
by zero and invalid input errors gracefully. LO3
Pseudocode:
try:
return result
except ZeroDivisionError:
Program:
def perform_division():
try:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except ValueError:
print("Error: Invalid input. Please enter valid numbers.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
Subject:
Year: FE Python Sem: II
Programming
perform_division()
OUTPUT: