Topics to be covered
1. Introduction
2. Types of errors
3.Handling Exceptions Using Try – Except –
Finally Blocks
1|Page
EXCEPTION HANDLING
While executing a Python program, it may happen that the program does not execute at all
or it can generate unexpected output. This happens when there are syntax errors, run time
errors, logical errors or any semantic errors in the code.
It occurs when we put some incorrect punctuation,
incorrect word sequence or there are some undefined
terms or missing parenthesis.
Syntax errors are also called as Parsing errors.
For example:
>>> p=2(num1+num2) This statement is
mathematically correct but python interpreter will
raise SYNTAX error as there is no sign present between
2 and parenthesis. The correct statement will be:
>>> p=2*(num1+num2)
Syntax Logical Run-time
It occurs when the It may occur when It occurs at the time
code is correct there may be some of program
according to syntax improper sequence execution. Such
but it is not of statements or errors produce
meaningful. The code incorrect use of incorrect output for
will not behave as operator. It will not specific values of
expected. stop a program input. These errors
For example: from executing but are also called
A = 10 will produce Exceptions, which
B = ”hello” incorrect output. It occur when
Result = A + B will generate something
Here, The code will incorrect output for unexpected happens
execute as it has every value of leading to stop the
correct syntax but will input. program execution.
not generate For example: For example:
expected output. If we want to find 5. Division by zero 6.
sum of two Finding square root
numbers and write of negative
the following code: number. EXCEPTIONS:
A, B = 10, 15 7. Insufficient Run time errors are
C=A*B memory available known as Exceptions.
print (“Sum is: “, C) on computer.
Here, the code will 8. Trying to open a
generate A * B but file that does not
we wanted to find exist.
Sum. Hence it is a
logical error.
When an Exception is generated, the program execution is stopped.
Removing errors from a code is referred to as EXCEPTION HANDLING.
Examples:
1. Division by zero
2. Performing an operation on incompatible types
3. Using an identifier variable which has not been defined
4. Accessing a list element, dictionary value or object attribute which does not exit
5. Trying to access a file that does not exist
Commonly occurring exceptions are usually defined in the Interpreter. These are
known as Built-in Exceptions.
Some Built-in Exceptions are listed as below:
EXCEPTION DESCRIPTION
ZeroDivisionError It is raised when an expression or a value is getting divided by zero
(0).
Eg) If c = 0, then p = b/c will result in ‘ZeroDivisionError’.
NameError It is raised when an identifier is not assigned any value earlier and is
being used in some expression.
Eg)A=10
B=20
print(A+C)
NameError: name 'c' is not defined
TypeError It is raised when an operator is provided with a value of different
datatype.
Eg)’cps’+4
TypeError: can only concatenate str (not "int") to str
ValueError It is raised when a built-in function receives an argument that has
the right type but an inappropriate value.
Eg: num=int(input(‘Enter a number’))
Enter a number: harsha
ValueError: invalid literal for int with base 10
IOError It is raised when the file specified in a program statement cannot be
opened.
Eg) f=open(‘xyz.txt’)
FileNotFoundError: No such file or directory: ‘xyz.txt’
IndexError It is raised when index of a sequence is out of the range.
Eg) L=[1,2,3]
print(L[5])
IndexError: list index out of range
KeyError It is raised when a key doesn’t exist or not found in a dictionary.
Eg)d={1:2}
print(d['a'])
KeyError: 'a'
AttributeError It is raised when an object does not find an attribute or method.
Eg: T=()
T.append(5)
AttributeError: 'tuple' object has no attribute 'append'
EOFError It is raised when one of the file methods .i.e. read(),readlines(),etc
tries to read beyond the file
EXCEPTION HANDLING:
Every exception has to be handled by the programmer for successful execution of the
program. To ensure this we write some additional code to give some proper message to the
user if such a condition occurs. This process is known as EXCEPTION HANDLING.
Exception handlers separate the main logic of the program from the error detection and
correction code. The segment of code where there is any possibility of error or exception, is
placed inside one block. The code to be executed in case the exception has occurred, is
placed inside another block. These statements for detection and reporting the execution do
not affect the main logic of the program.
STEPS FOR EXCEPTION HANDLING:
Example 1:
53 | P a g e
The output will be:
Example 2:
In above example, the user entered a wrong value that raised ValueError. We can handle
this exception by using ValueError exception.
Result:
Use of multiple “except” block:
Sometimes, it may happen that a single piece of code in a program might have more than
one type of error. If such an event happens, we can use multiple except blocks for a single
try block.
Example 1:
54 | P a
ge
The output will be:
Example 2:
We can also handle exceptions without naming them.
The output will be:
Default exception messages can also be displayed when we are not handling exceptions by
name.
try…except…else Clause:
Just like Conditional and Iterative statements we can use an optional else clause along with
the try…except clause. An except block will be executed only when some exceptions will be
raised in the try block. But if there is no error then except blocks will not be executed. In this
case, else clause will be executed.
Example:
The output will be:
finally CLAUSE:
The try…except…else block in python has an optional finally clause. The statements inside the finally
block are always executed whether an exception has occurred in the try block or not. If we want to
use finally block, it should always be placed at the end of the clause i.e. after all except blocks and
the else block.
The outputs will be:
Note: finally clause can be written without else clause .i.e. try----except-----finally
Raising Exceptions/User-Defined Exceptions:
Each time an error is detected in a program, the Python interpreter raises (throws) an exception.
* Programmers can also forcefully raise exceptions in a program using the raise and assert
statements.
* Once an exception is raised, no further statement in the current block of code is executed.
* So, raising an exception involves interrupting the normal flow execution of program.
Output:
assert statement
Python has built-in assert statement to use assertion condition in the program.
assert statement has a condition or expression which is supposed to be always true. If the
condition is false assert halts the program and gives an AssertionError.
Example:
Output:
Exercise
1 In a try-except block, can there be multiple 'except' clauses? a)
No, there can be only one 'except' clause.
b) Yes, but only if the exceptions are of the same type.
c) Yes, it allows handling different exceptions separately.
d) No, 'except' clauses are not allowed in a try-except block.
2 When might you use the 'finally' block in exception handling? a) To
handle exceptions that are expected to occur frequently.
b) To provide a resolution for every possible error.
c) To close resources that were opened in the 'try' block, regardless of whether an
exception occurred or not.
d) To avoid having to use 'except' blocks.
3 What will be the output of the following code snippet?
a) Division by zero!
b) Arithmetic error occurred!
c) No error!
d) This code will raise a syntax error.
4 Which of the following is NOT a standard built-in exception in Python? a)
ValueError
b) IndexError
c) NullPointerException
d) KeyError
5 What is an exception in programming?
a) An error that occurs during runtime
b) A warning message from the compiler
c) A comment in the code
d) A statement that terminates the program
6 What is the purpose of the "try" block in a try-except construct? a) To
handle the exception by executing specific code
b) To specify the type of exception to be thrown
c) To define a custom exception class
d) To ensure a specific block of code always executes
7 Which of the following exceptions in Python is not a built-in exception? a)
ValueError
58 | P a g e
b) KeyError
c) CustomError
d) IndexError
8 Assertion (A): In Python, the "try" block is used to enclose code that might raise an
exception.
Reasoning (R): The "try" block is where the program attempts to execute code that
might result in an exception. If an exception occurs, it is handled in the
corresponding "except" block.
A. Both A and R are true and R is correct explanation of A
B. Both A and R are true but R is not correct explanation of A
C. A is True but R is False
D. R is True but A is False
9 Assertion (A): The "finally" block in Python is always executed, regardless of whether an
exception is raised or not.
Reasoning (R): The "finally" block contains code that is guaranteed to execute,
whether an exception occurs within the "try" block or not.
A. Both A and R are true and R is correct explanation of A
B. Both A and R are true but R is not correct explanation of A
C. A is True but R is False
D. R is True but A is False
10 Assertion (A): Python allows multiple "except" blocks to be used within a single "try"
block to handle different exceptions.
Reasoning (R): By using multiple "except" blocks with different exception types,
Python provides the flexibility to handle various types of exceptions separately. A.
Both A and R are true and R is correct explanation of A
B. Both A and R are true but R is not correct explanation of A
C. A is True but R is False
D. R is True but A is False
11 Code snippet:
Predict the output when:
a) The user enters "0" .
b) The user enters "5".
c) The user enters "abc".
12 State whether the following statement is True or False: An exception may be raised
even if the program is syntactically correct.
13 What will be the output of the following code if the input is “e”:
59 | P a g e
try:
value = int("abc")
result = 10 / 0
except ValueError:
print("Error: Invalid value conversion")
except ZeroDivisionError:
print("Error: Division by zero")
14 What will be the output of the following code if the input is: i. 2
ii. 2.2
try:
num = int(input("Enter a number: "))
except ValueError:
print("Error: Invalid input")
else:
print("Entered number: ",num)
15 Rewrite the following code after handling all possible exceptions.
num = int(input("Enter a number: "))
result = 10 / num
print("Result:", result)
16 Consider the code given below:
L = [‘s’, 45,23]
Result = 0
for x in L:
print (“The element is “, x)
Result += x
print(“The addition of all elements of L is: “, Result)
Which of the following error will be raised by the given Python
code? a) NameError
b) ValueError
c) TypeError
d) IOError
17 Code snippet:
Predict the output when:
a) The user enters "10" for both numbers.
60 | P a g e
b) The user enters "5" for the first number and "0" for the second number.
c) The user enters "abc" for both numbers.
18 Which of the following statements is true?
a). The standard exceptions are automatically imported in Python
programs. b). All raised standard exceptions must be handled in Python.
c). When there is deviation from the rules of a programming language, a semantic
error is thrown.
d). If any exception is thrown in try block, else block is executed.
19 Identify the statement(s) from the following options which will raise TypeError
exception(s):
a) print('5')
b) print( 5 * 3)
c) print('5' +3)
d) print('5' + '3')
Programming based question:
1 Create a simple calculator program that takes two numbers and an operator (+, -, *, /)
as input. Implement exception handling to handle cases like division by zero and
invalid operators.
2 Build a program that asks the user for an integer input. Use exception handling to
ensure that the input is a valid integer. If the user provides invalid input, prompt
them to retry until a valid integer is entered.
3 Create a program that connects to a database and performs database operations (e.g.,
insert, update, delete). Use exception handling to deal with database-related
exceptions, such as connection errors or SQL syntax error.
4 Create a program that reads data from a file specified by the user. Implement exception
handling to catch and handle the "FileNotFoundError" exception if the file does
not exist.
5 Define a dictionary with some key-value pairs. Ask the user for a key and attempt to
access the corresponding value from the dictionary. Handle the "KeyError"
exception and display a message if the key is not found.
61 | P a g e