Key Points
Introduction:
Sometimes while executing a Python program, the program does not execute at all or the
program executes but generates unexpected output or behaves abnormally.
These occur when there are syntax errors, runtime errors or logical errors in the code.
➤ Syntax Errors are also known as Parsing Errors.
Run time Errors are also known as Exceptions.
Exceptions:
Even if a statement or expression is syntactically correct, there might arise an error during its
execution.
➤ For example, trying to open a file that does not exist, division by zero and so on.
➤ Such types of errors might disrupt the normal execution of the program and are
called exceptions.
When an error occurs during the execution of a program, an exception is said to have been
raised.
Such an exception needs to be handled by the programmer so that the program does not
terminate abnormally.
Built-In Exceptions in Python:
➤Commonly occurring exceptions are defined in the usually compiler/interpreter.
These are called built-in exceptions.
➤ Python's standard library is an extensive collection of built-in exceptions that
deals with the commonly occurring
errors (exceptions) by providing the standardized solutions for such errors.
1. SyntaxError: It is raised when there is an error in the syntax of the Python code.
2. ValueError: It is raised when a built-in method or operation receives an argument that has the
right data type but mismatched or inappropriate values.
3. IOError: It is raised when the file specified in a program statement cannot be opened.
4. KeyboardInterrupt: It is raised when the user accidentally hits the Delete or Esc key while
executing a program due to which the normal flow of the program is interrupted.
5. ImportError: It is raised when the requested is not found.
6. EOFError: It is raised when the end of file condition is reached without reading any data by
input().
7. ZeroDivisionError: It is raised when the denominator in a division operation is zero.
8. IndexError: It is raised when the index or subscript in a sequence is out of range.
9. NameError: It is raised when a local or global variable name is not defined.
10. TypeError: It is raised when an operator is supplied with a value of incorrect data type.
Handling Exceptions:
Each and every exception has to be handled by the programmer to avoid the program from
crashing abruptly.
This is done by writing additional code in a program to give proper messages or instructions to
the user on encountering an exception.
➤ This process is known as exception handling.
Need for Exception Handling:
➤ Python categorises exceptions into distinct types so that specific exception
handlers (code to handle that particular exception) can be created for each type.
➤ The compiler or interpreter keeps track of the exact position where the error has
occurred.
➤ The compiler or interpreter keeps track of the exact position where the error has
occurred.
➤ 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 exception do not affect the main logic of the program.
Catching Exceptions:
➤ An exception is said to be caught when a code that is designed to handle a
particular exception is executed.
➤ Exceptions, if any, are caught in the try block and handled in the except block.
➤ While writing or debugging a program, a user might doubt an exception to occur
in a particular part of the code. Such suspicious lines of codes are put inside a try
block. Every try block is followed by an except block.
➤ The appropriate code to handle each of the possible exceptions (in the code
inside the try block) are written inside the except clause.
➤ While executing the program, if an exception is encountered, further execution of
the code inside the try block is stopped and the control is transferred to the except
block.
Use of multiple except blocks:
➤ Sometimes, a single piece of code might be suspected to have more than one
type of error.
➤ For handling such situations, we can have multiple except blocks for a single try
block.
In the code, two types of exceptions (ZeroDivisionError and ValueError) are handled using two
except blocks for a single try block. When an exception is raised, a search for the matching
except block is made till it is handled. If no match is found, then the program terminates.
*In the code, two types of exceptions (ZeroDivisionError and ValueError) are handled using two
except blocks for a single try block.
*When an exception is raised, a search for the matching except block is made till it is handled. If
no match is found, then the program terminates.
try....except....else clause
We can put an optional else clause along with the try....except clause.
An except block will be executed only if some exception is raised in the try block.
But if there is no error then none of the except blocks will be executed. In this case, else clause
will be executed.
finally clause:
The try statement in Python can also have an optional finally clause.
The statements inside the finally block are always executed regardless of whether an exception
has occurred in the try block or not.
If used, finally should always be placed at the end of try clause, after all except blocks and the
else block.
Multiple Choice Questions
What will be the output of the following Python Code?
1)a = 5.2
try:
print(a)
except NameError:
print("Variable a is not defined.")
except ValueError:
print("The value of a must be an integer")
(a) The value of a must be an integer.
(b) Variable a is not defined.
(c) 5.2
(d) No Output
2. Which of the following error will be raised by the given Python Code?
L=['a',2,3]
for element in L:
print("The element is", element)
x=int(element+1)
print("The increment of ",element, "is",x)
(a) NameError
(b) ValueError
(c) TypeError
(d) IOError
3. Which of the following Python Error will be raised by the given Python Code?
X=10
Y=20
if (y>x)
print("y is greater than x")
(a) NameError
(b) ValueError
(c) TypeError
(d) SyntaxError
4. 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 a 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.
5. Which of the following is not the standard
exception in Python?
(a) NameError
(b) AttributeError
(c) AssignmentError
(d) ZeroDivisionError
6. Syntax Errors are also known as....
(a) Logical Errors
(b) Parsing Errors
(e) Code Errors
(d) Programming Errors
7. It is raised when a built in method or operation receives an argument that has the right
data type but mismatched or inappropriate values.
(a) NameError
(b) ValueError
(e) LogicalError
(d) SyntaxError
8. It is raised when a file specified in a program statement cannot be opened.
a) IOError
b) OverFlowError
c) IndexError
d) NameError
9. It is used when a user accidently hits the delete or Esc key while executing a program
due to which the normal flow of the program
is interrupted.
a) IOError
b) OverFlowError
c) KeyboardInterrupt
d) SyntaxError
10. When you accept a string, instead of an integer value, _____is raised.
(a) TypeError
(b) ValueError
(c) NameError
(d) SyntaxError
11. What will following python code produce?
x=5
y=0
print('A')
try:
print('B')
a=x/y
print ©
except ZeroDivisionError:
print ('F')
except:
print ('D')
12. Consider the statements given below and then choose the correct output from the
given options:
N='5'
try:
print('WORD'+N, end=’#’)
except:
print('ERROR',end='#')
finally:
print('OVER')
(a) ERROR#
(b) WORD5#OVER
(c) WORDS#
(d) ERROR#OVER
Objective Type Questions.
State whether the following statement is True or False.
1. An exception may be raised even if the program is syntactically correct.
2. Syntax errors or parsing errors are detected when we have not followed the rules of
the particular programming language while writing a program.
3. An exception is a Python object that represents an error.
4. While handling exceptions in Python, name of the exception has to be compulsorily
added with except clause.
Fill in the blanks.
5. Syntax Errors are also known as_____
6. An ____ is a Python object that represents an error.
7. _____ are the codes that are designed to execute when a specific exception is raised.
8. _____and _____ statements are used to raise exceptions.
9. An exception is caught in the ___ block and handles in ____ block.
10. The statements inside the ____ block are always executed regardless of whether an
exception occurred in the try block or not.
11. The optional _____clause contains codes to be executed if no exception occurs. The
optional finally block contains codes to be executed irrespective of whether an exception
occurs or not.