Experiment No.
11
Name of Experiment: Handle errors and exceptions in Python programs, ensuring
robust and fault-tolerant code.
Aim of Experiment: Write a Python program to implement exception handling.
Date of Performance:
Date of Submission:
Rubrics for Internal Evaluation:
Sr.
Rubrics Weightage
No.
1 Attendance (2)
2 Performance of experiment and Oral(3)
3 Journal Writing (3)
4 Timely Submission (2)
Total (10)
Practical In-charge
Experiment No. 11
Aim of Experiment:
Write a Python program to implement exception handling.
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 to catch and manage errors, making the code more robust and user-
friendly.
An occurrence that arises during the execution of a program and disrupts its normal
flow is referred to as an exception. To safeguard the program from abrupt termination,
Python generates exceptions during program execution. These exceptions in the Python
programming language can either arise automatically due to errors or can be
deliberately provoked and handled by the code which we write.
Python handles exceptions using the "try" and "except" blocks. The code that might
cause an exception is placed within the "try" block, and potential exceptions are caught
and managed in the corresponding "except" blocks.
Common Examples of Exception:
● Division by Zero
● Accessing a file that does not exist.
● Addition of two incompatible types
● Trying to access a non-existent index of a sequence
● Removing the table from the disconnected database server.
● ATM withdrawal of more than the available amount
Here are the reasons for using exceptions in Python:
● Exception handling in python allows to separate error-handling code from normal code.
● An exception is a Python object which represents an error.
As with code comments, exceptions helps to remind of what the program expects.
It clarifies the code and enhances readability.
Allows to stimulate consequences as the error-handling takes place in one place and in
one manner.
An exception is a convenient method for handling error messages.
Types of Errors in Python
● Syntax errors: Syntax errors occur when the code violates the rules of the
Python language syntax. These errors are detected by the Python interpreter when it is
parsing the code. (Missing colon, Unmatched parentheses, Missing quotes, Using a keyword
as a variable name, Missing indentation)
● Runtime errors: Runtime errors occur when the code is syntactically correct but causes
an error when it is executed. These errors can be caused by a variety of reasons, such as
invalid input data, division by zero, or accessing an undefined variable.
● Logical errors: Logical errors occur when the code is syntactically correct and runs
without causing any errors, but the output is not what expected. These errors can be
caused by incorrect algorithmic design, mathematical errors, or a misunderstanding of
the problem requirements.
Build-in exceptions in python
1) SyntaxError: Raised when there is a syntax error in the Python code
2) TypeError: Raised when an operation or function is applied to an object of inappropriate
type.
3) ValueError: Raised when a built-in operation or function receives an argument that has
the right type but an inappropriate value.
4) IndexError: Raised when trying to access an index that does not exist in a sequence.
5) KeyError: Raised when trying to access a key that does not exist in a dictionary.
6) NameError: Raised when a variable name is not defined.
7) AttributeError: Raised when trying to access an attribute that does not exist.
8) IOError: Raised when an input/output operation fails.
9) ZeroDivisionError: Raised when trying to divide a number by zero.
10) MemoryError: Creating a large list or array that exceeds the available memory
11) ImportError: Raised when an import statement fails to find and load the requested
module.
Python Exception Handling Mechanism
Exception handling in python is managed by the following 3 keywords:
● Try
● Except
● Else
Python try...except Block
The try...except block is used to handle exceptions in Python. Here's the syntax
of try...except block:
Here, we have placed the code that might generate an exception inside the try block.
Every try block is followed by an except block.
When an exception occurs, it is caught by the except block. The except block cannot be
used without the try block.
Example: Exception Handling Using try...except
In the example, we are trying to divide a number by 0. Here, this code generates an
exception.
To handle the exception, we have put the code, result = numerator/denominator inside
the try block. Now when an exception occurs, the rest of the code inside the try block is
skipped.
The except block catches the exception and statements inside the except block are
executed.
If none of the statements in the try block generates an exception, the except block is
skipped.
For each try block, there can be zero or more except blocks. Multiple except blocks
allow us to handle each exception differently.
The argument type of each except block indicates the type of exception that can be
handled by it. For example,
In this example, we have created a list named even_numbers.
Since the list index starts from 0, the last element of the list is at index 3. Notice the
statement,
Here, we are trying to access a value to the index 5.
Hence, IndexError exception occurs.
When the IndexError exception occurs in the try block,
The ZeroDivisionError exception is skipped.
The set of code inside the IndexError exception is executed.
Python try with else clause
In some situations, we might want to run a certain block of code if the code block
inside try runs without any errors.
For these cases, we can use the optional else keyword with the try statement.
Let's look at an example:
Output
If we pass an odd number:
Enter a number: 1
Not an even number!
If we pass an even number, the reciprocal is computed and displayed.
Enter a number: 4
0.25
However, if we pass 0, we get ZeroDivisionError as the code block inside else is not
handled by preceding except
Program Code:
1. 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:
try:
x = int(input("Enter first number: "))
y = int(input("Enter second number: "))
result = x / y
except ZeroDivisionError:
print("Error: Division by zero is not allowed")
except ValueError:
print("Error: Invalid input. Please enter a numeric value.")
else:
print("Result:", result)
finally:
print("Execution completed.")
Output:
2. Demonstrate the use of a Python debugger (e.g., pdb or an IDE with
debugging capabilities) on a sample program with intentional errors.