0% found this document useful (0 votes)
9 views19 pages

PP I3 Expt5 RN41

The document outlines an experiment focused on implementing exception handling in Python to manage division by zero and invalid input errors, along with demonstrating the use of a Python debugger. It provides theoretical explanations of exception handling, common exceptions, and debugging techniques using the pdb module. The experiment includes practical coding tasks for students to apply these concepts and manage errors effectively in their programs.

Uploaded by

sajusaj987654321
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views19 pages

PP I3 Expt5 RN41

The document outlines an experiment focused on implementing exception handling in Python to manage division by zero and invalid input errors, along with demonstrating the use of a Python debugger. It provides theoretical explanations of exception handling, common exceptions, and debugging techniques using the pdb module. The experiment includes practical coding tasks for students to apply these concepts and manage errors effectively in their programs.

Uploaded by

sajusaj987654321
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

EXPERIMENT NO.

5
[PART A]
Name of the experiment: Implementation exception handling to manage division by
zero and invalid input errors gracefully and Demonstration of a Python debugger.
Aim:
a)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.
b)Demonstrate the use of a Python debugger (e.g., pdb or an IDE with debugging capabilities) on
a sample program with intentional errors. Guide students on setting breakpoints, stepping
through code, and examining variable values.

Theory:

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.
# Example of an exception
n = 10
try:
res = n / 0 # This will raise a ZeroDivisionError

except ZeroDivisionError:
print("Can't be divided by zero!")

Output
Can't be divided by zero!
Explanation: In this example, dividing number by 0 raises a ZeroDivisionError. The try block
contains the code that might cause an exception and the except block handles the exception,
printing an error message instead of stopping the program.
Difference Between Exception and Error
● Error: Errors are serious issues that a program should not try to handle. They are usually
problems in the code’s logic or configuration and need to be fixed by the programmer.
Examples include syntax errors and memory errors.
● Exception: Exceptions are less severe than errors and can be handled by the program. They
occur due to situations like invalid input, missing files or network issues.
Example:
# Syntax Error (Error)
print("Hello world" # Missing closing parenthesis

# ZeroDivisionError (Exception)
n = 10
res = n / 0
Explanation: A syntax error is a coding mistake that prevents the code from running. In
contrast, an exception like ZeroDivisionError can be managed during the program’s execution
using exception handling.
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 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).
Example:
try:
n=0
res = 100 / n

except ZeroDivisionError:
print("You can't divide by zero!")

except ValueError:
print("Enter a valid number!")

else:
print("Result is", res)

finally:
print("Execution complete.")

Output
You can't divide by zero!
Execution complete.
Explanation:
● try block asks for user input and tries to divide 100 by the input number.
● except blocks handle ZeroDivisionError and ValueError.
● else block runs if no exception occurs, displaying the result.
● finally block runs regardless of the outcome, indicating the completion of execution.
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 Name Description

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 with zero


ZeroDivisionError as the divisor.

Raised when a numerical operation exceeds the maximum limit of a


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

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 of


TypeError inappropriate type.

Raised when a function receives an argument of the right type but


ValueError inappropriate value.

ImportError Raised when an import statement has issues.

ModuleNotFoundError Raised when a module cannot be found.

Python Catching Exceptions


When working with exceptions in Python, we can handle errors more efficiently by specifying
the types of exceptions we expect. This can make code both safer and easier to debug.
Catching Specific Exceptions
Catching specific exceptions makes code to respond to different exception types differently.
Example:
try:
x = int("str") # This will cause ValueError
#inverse
inv = 1 / x

except ValueError:
print("Not Valid!")

except ZeroDivisionError:
print("Zero has no inverse!")

Output
Not Valid!
Explanation:
● The ValueError is caught because the string “str” cannot be converted to an integer.
● If x were 0 and conversion successful, the ZeroDivisionError would be caught when
attempting to calculate its inverse.
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.
Example:
a = ["10", "twenty", 30] # Mixed list of integers and strings
try:
total = int(a[0]) + int(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.
Catch-All Handlers and Their Risks
Here’s a simple calculation that may fail due to various reasons.
Example:
try:
# Simulate risky calculation: incorrect type operation
res = "100" / 20

except ArithmeticError:
print("Arithmetic problem.")

except:
print("Something went wrong!")

Output
Something went wrong!
Explanation:
● An ArithmeticError (more specific like ZeroDivisionError) might be caught if this were a
number-to-number division error. However, TypeError is actually triggered here due to
attempting to divide a string by a number.
● catch-all except: is used to catch the TypeError, demonstrating the risk that the programmer
might not realize the actual cause of the error (type mismatch) without more detailed error
logging.
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:
● Improved program reliability: By handling exceptions properly, you can prevent your
program from crashing or producing incorrect results due to unexpected errors or input.
● Simplified error handling: Exception handling allows you to separate error handling code
from the main program logic, making it easier to read and maintain your code.
● Cleaner code: With exception handling, you can avoid using complex conditional
statements to check for errors, leading to cleaner and more readable code.
● Easier debugging: When an exception is raised, the Python interpreter prints a traceback
that shows the exact location where the exception occurred, making it easier to debug your
code.
Disadvantages of Exception Handling:
● Performance overhead: Exception handling can be slower than using conditional
statements to check for errors, as the interpreter has to perform additional work to catch and
handle the exception.
● Increased code complexity: Exception handling can make your code more complex,
especially if you have to handle multiple types of exceptions or implement complex error
handling logic.
● Possible security risks: Improperly handled exceptions can potentially reveal sensitive
information or create security vulnerabilities in your code, so it’s important to handle
exceptions carefully and avoid exposing too much information about your program.
Debugging in Python is facilitated by pdb module (python debugger) which comes built-in to
the Python standard library. It is actually defined as the class Pdb which internally makes use of
bdb(basic debugger functions) and cmd (support for line-oriented command interpreters)
modules. The major advantage of pdb is it runs purely in the command line, thereby making it
great for debugging code on remote servers when we don’t have the privilege of a GUI-based
debugger.
pdb supports:
● Setting breakpoints
● Stepping through code
● Source code listing
● Viewing stack traces
Starting Python Debugger
There are several ways to invoke a debugger
● To start debugging within the program just insert import pdb,
pdb.set_trace() commands. Run your script normally, and execution will stop where we have
introduced a breakpoint. So basically we are hard coding a breakpoint on a line below where
we call set_trace(). With python 3.7 and later versions, there is a built-in function
called breakpoint() which works in the same manner. Refer following example on how to
insert set_trace() function.
Example1: Debugging a Simple Python program of addition of numbers using Python
pdb module
Intentional error: As input() returns string, the program cannot use multiplication on strings.
Thus, it’ll raise ValueError.
● Python3

import pdb

def addition(a, b):

answer = a * b

return answer

pdb.set_trace()

x = input("Enter first number : ")

y = input("Enter second number : ")


sum = addition(x, y)

print(sum)

Output :

set_trace

In the output on the first line after the angle bracket, we have the directory path of our file, line
number where our breakpoint is located, and <module>. It’s basically saying that we have a
breakpoint in exppdb.py on line number 10 at the module level. If you introduce the breakpoint
inside the function, then its name will appear inside <>. The next line is showing the code line
where our execution is stopped. That line is not executed yet. Then we have the pdb prompt.
Now to navigate the code, we can use the following commands :

Command Function

help To display all commands

where Display the stack trace and line number of the current line

next Execute the current line and move to the next line ignoring function calls

step Step into functions called at the current line

Now, to check the type of variable, just write whatis and variable name. In the example given
below, the output of type of x is returned as <class string>. Thus typecasting string to int in our
program will resolve the error.
Example 2: Checking variable type using pdb ‘whatis’ command
We can use ‘whatis‘ keyword followed by a variable name (locally or globally defined) to find
its type.
● Python3

a = 20

b = 10
s=0

for i in range(a):

# this line will raise ZeroDivision error

s += a / b

b -= 1

Finding variable type using whatis command in pdb

● From the Command Line: It is the easiest way of using a debugger. You just have to run
the following command in terminal
python -m pdb exppdb.py (put your file name instead of exppdb.py)
This statement loads your source code and stops execution on the first line of code.
Example 3: Navigating in pdb prompt
We can navigate in pdb prompt using n (next), u (up), d (down). To debug and navigate all
throughout the Python code, we can navigate using the mentioned commands.

● Python3

a = 20

b = 10

s=0

for i in range(a):

s += a / b

b -= 1

Output :

Navigate in pdb prompt using commands

Example 4: Post-mortem debugging using Python pdb module


Post-mortem debugging means entering debug mode after the program is finished with the
execution process (failure has already occurred). pdb supports post-mortem debugging through
the pm() and post_mortem() functions. These functions look for active trace back and start the
debugger at the line in the call stack where the exception occurred. In the output of the given
example, you can notice pdb appear when an exception is encountered in the program.
● Python3

def multiply(a, b):

answer = a * b

return answer
x = input("Enter first number : ")

y = input("Enter second number : ")

result = multiply(x, y)

print(result)

Output :

Checking variables on the Stack


All the variables including variables local to the function being executed in the program as well
as global are maintained on the stack. We can use args(or use a) to print all the arguments of a
function which is currently active. p command evaluates an expression given as an argument and
prints the result.
Here, example 4 of this article is executed in debugging mode to show you how to check for
variables :
checking variable values

Python pdb Breakpoints


While working with large programs, we often want to add a number of breakpoints where we
know errors might occur. To do this you just have to use the break command. When you insert a
breakpoint, the debugger assigns a number to it starting from 1. Use the break to display all the
breakpoints in the program.
Syntax:
break filename: lineno, condition
Given below is the implementation to add breakpoints in a program used for example 4.

Adding_breakpoints

Managing Breakpoints
After adding breakpoints with the help of numbers assigned to them, we can manage the
breakpoints using the enable and disable and remove command. disable tells the debugger not
to stop when that breakpoint is reached, while enable turns on the disabled breakpoints.
Given below is the implementation to manage breakpoints using Example 4.

[PART B]

Write a code for the following programs and execute it. After the code paste
screenshot of the output of the program.

a)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.
b)Demonstrate the use of a Python debugger (e.g., pdb or an IDE with debugging capabilities) on
a sample program with intentional errors. Guide students on setting breakpoints, stepping
through code, and examining variable values.
a)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.

Program code(Input):

OUTPUT:
b)Demonstrate the use of a Python debugger (e.g., pdb or an IDE with debugging
capabilities) on a sample program with intentional errors. Guide students on setting
breakpoints, stepping through code, and examining variable values.

Program code(Input)with error:

OUTPUT(with error):
Program code(Input)after correcting error:

OUTPUT:
Conclusion:

Sahil SHAIKH (I41)


FE/SEM2/MTRX
I3

MTRX / I3 / SEM2
BRANCH/BATCH/SEM
41
ROLL NO
18 / 02 2025
DATE OF EXPERIMENT
21 / 02 /2025
DATE OF SUBMISSION

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy