1 Exception Handling
1 Exception Handling
Exceptions
• An exception is a Python object that represents an error.
• 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 alter 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 be raised.
• Such an exception needs to be handled by the programmer so that the program does not terminate abnormally.
• Therefore, while designing a program, a programmer may except such error situations and handle that exception.
Built-in Exceptions
• These are the commonly occurring exceptions, which are defined in the compiler/interpreter.
• 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.
• On the occurrence of any built-in exception, the appropriate exception handler code is executed which displays the reason along
with the raised exception name.
• The programmer then has to take appropriate action to handle it.
• Some of the commonly occurring built-in exceptions that can be raised in Python are explained in following table.
Name of the
S. No Explanation
Builtin exception
1 SyntaxError It is raised when there is an error in the syntax of the Python code.
It is raised when a built-in method or operation receives an argument that has the right data type
2 ValueError
but mismatched or inappropriate values.
3 IOError It is raised when the file specified in a program statement cannot be opened.
It is raised when the user accidentally hits the Delete or Esc key while executing a program due to
4 KeyboardInterrupt
which the normal flow of the program is interrupted.
5 ImportError It is raised when the requested module definition 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 IndentationError It is raised due to incorrect indentation in the program code.
11 TypeError It is raised when an operator is supplied with a value of incorrect data type.
12 OverFlowError It is raised when the result of a calculation exceeds the maximum limit for numeric data type.
Example 1:
Example 2:
Example 3:
Raising exceptions
User-defined exceptions: The exceptions created by user or programmer according to their requirements are called user-defined
exceptions.
• Programmers can raise exceptions using the raise and assert statements.
• Once an exception is raised, no further statement in the current block of code is executed.
• Raising an exception involves interrupting the normal flow execution and jumping to that part of the program (exception
handler code) which is written to handle such exceptional situations.
The raise Statement: The raise statement is used to throw an exception.
Syntax: raise exception-name [(optional argument)]
Here,
The argument is generally a string that is displayed when the exception is raised.
When an exception is raised, the message “Alert !! An exception has occurred” is displayed along with a brief description of the error.
Output:
Output:
Example 2:
Output:
Traceback stack
• This is a structured block of text that contains information about the sequence of function calls in execution of code in which
the exception was raised.
Handling exceptions
• It is the process of writing additional code in a program to give proper message or instructions to the user when an exception
occurred.
• Exceptions are handled by the programmer to avoid the program from crashing, abnormal execution.
List of definitions
1) Run time system
• It refers to the process of execution of statements given in the program.
• Execution of statement is complex mechanism which includes hardware and software.
2) exception object: It is an object created by python interpreter when an error occurs, which stores details about error generated.
3) Throwing an exception: process of creating an exception object and handling it over to the runtime system is called as throwing
an exception.
4) Exception handler: Its is a code segment in a program written to handle the raised exceptions.
5) Call stack: It is a list which contains all the methods, functions written in a python program.
6) Catching the exception: The process of executing a suitable exception handle code by the run time system is called as catching
expression.
Catching exception
• An exception is said to be caught when a code that is described to handle a particular exception is executed.
Output 1:
Output 2:
Output 1:
Output 2:
Output 3:
Example:
Output:
try...except…else clause
• The else clause in try-except-else clause is used to execute the statements if there is no exception raised in try block.
• An except block will be executed only if some exception is raised in the try block.
Example:
Output 1:
Output 2:
Output 3:
Finally Clause
• It is an optional clause which is used to execute statements regardless of whether an exception has occurred in the try block or
not.
• It is usually used, while working with files to ensure that the file object is closed.
• Finally clause should always be written after all except blocks and the else block.
Example:
Output:
Example:
Output: