PP I3 Expt5 RN41
PP I3 Expt5 RN41
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
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 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
answer = a * b
return answer
pdb.set_trace()
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
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
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):
s += a / b
b -= 1
● 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 :
answer = a * b
return answer
x = input("Enter first number : ")
result = multiply(x, y)
print(result)
Output :
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.
OUTPUT(with error):
Program code(Input)after correcting error:
OUTPUT:
Conclusion:
MTRX / I3 / SEM2
BRANCH/BATCH/SEM
41
ROLL NO
18 / 02 2025
DATE OF EXPERIMENT
21 / 02 /2025
DATE OF SUBMISSION