0% found this document useful (0 votes)
11 views5 pages

PPL Experiment No-9

The document outlines the principles of error handling and exception management in Python, emphasizing the use of try, except, else, and finally blocks. It details common exceptions such as ZeroDivisionError and provides a practical example of a Python program that performs division while managing exceptions for division by zero and invalid inputs. The document also includes an algorithm and pseudocode to illustrate the implementation of exception handling in a division operation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views5 pages

PPL Experiment No-9

The document outlines the principles of error handling and exception management in Python, emphasizing the use of try, except, else, and finally blocks. It details common exceptions such as ZeroDivisionError and provides a practical example of a Python program that performs division while managing exceptions for division by zero and invalid inputs. The document also includes an algorithm and pseudocode to illustrate the implementation of exception handling in a division operation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

Subject:

Year: FE Python Sem: II


Programming

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.

Syntax and Usage

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
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).

Common Exceptions in Python

Python has many built-in exceptions, each representing a specific error condition. Some common
ones include:

Exception Name Description

BaseException The base class for all built-in exceptions.

Exception The base class for all non-exit exceptions.

ArithmeticError Base class for all errors related to arithmetic operations.

Raised when a division or modulo operation is performed


ZeroDivisionError
with zero as the divisor.

Raised when a numerical operation exceeds the maximum


OverflowError
limit of a data type.

FloatingPointError Raised when a floating-point operation fails.

AssertionError Raised when an assert statement fails.

AttributeError Raised when an attribute reference or assignment fails.

IndexError Raised when a sequence subscript is out of range.

KeyError Raised when a dictionary key is not found.


Subject:
Year: FE Python Sem: II
Programming
MemoryError Raised when an operation runs out of memory.

NameError Raised when a local or global name is not found.

OSError Raised when a system-related operation (like file I/O) fails.

Raised when an operation or function is applied to an object


TypeError
of inappropriate type.

Raised when a function receives an argument of the right type


ValueError
but inappropriate value.

ImportError Raised when an import statement has issues.

ModuleNotFoundError Raised when a module cannot be found.

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

Algorithm to handle divide by zero exception in Python:

1. Input: Two numbers: numerator and denominator.


2. Try to Perform the Division:
○ Use a try block to attempt the division.
3. Handle Zero Denominator:
○ If the denominator is zero, Python will raise a ZeroDivisionError.
○ Use an except block to catch this exception and handle it (e.g., print a message or
return a special value).
4. Output: The result of the division or an error message if the denominator is zero.
Subject:
Year: FE Python Sem: II
Programming

Pseudocode:

function divide(numerator, denominator):

try:

result = numerator / denominator

return result

except ZeroDivisionError:

print("Error: Division by zero is not allowed.")

return None # Or return any special value like NaN or infinity

Program:

def perform_division():
try:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

result = num1 / num2

print(f"The result of {num1} / {num2} is: {result}")

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:

Enter the first number: 10


Enter the second number: 0
Error: Division by zero is not allowed.

You might also like