Exception Handling
Exception Handling
Introduction
In Python, exceptions are errors that get triggered automatically.
However, exceptions can be forcefully triggered and handled through program code.
Syntax Errors
Syntax errors are detected when we have not followed the rules of the particular programming language while writing
a program. These errors are also known as parsing errors.
When a syntax error is encountered while working in shell mode, Python displays the name of the error and a small
description about the error
Similarly, when a syntax error is encountered while running a program in script mode a dialog box specifying the name of
the error and a small description about the error is displayed.
Exceptions
Built-in Exceptions
• Commonly occurring exceptions are usually defined in the 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.
NOTE :
A programmer can also create custom exceptions to suit one’s requirements. These are called user-defined
exceptions.
Different types of exceptions in python:
• SyntaxError: This exception is raised when the interpreter encounters a syntax error in the code, such as a
misspelled keyword, a missing colon, or an unbalanced parenthesis.
• TypeError: This exception is raised when an operation or function is applied to an object of the wrong
type, such as adding a string to an integer.
• NameError: This exception is raised when a variable or function name is not found in the current scope.
• IndexError: This exception is raised when an index is out of range for a list, tuple, or other sequence
types.
• KeyError: This exception is raised when a key is not found in a dictionary.
• ValueError: This exception is raised when a function or method is called with an invalid argument or
input, such as trying to convert a string to an integer when the string does not represent a valid integer.
• AttributeError: This exception is raised when an attribute or method is not found on an object, such as
trying to access a non-existent attribute of a class instance.
• IOError: This exception is raised when an I/O operation, such as reading or writing a file, fails due to an
input/output error.
• ZeroDivisionError: This exception is raised when an attempt is made to divide a number by zero.
• ImportError: This exception is raised when an import statement fails to find or load a module.
Raising Exceptions
• Each time an error is detected in a program, the Python interpreter raises (throws) an exception.
• Exception handlers are designed to execute when a specific exception is raised. 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 and jumping to that part of the
program (exception handler code) which is written to handle such exceptional situations.
• 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.
• The compiler or interpreter keeps track of the exact position where the error has occurred.
• Exception handling can be done for both user-defined and built-in exceptions.
Catching Exceptions
• An exception is said to be caught when a code that is designed to handle a particular exception is executed.
• Exceptions are caught in the try block and handled in the except block.
• Every try block is followed by an except block.
• 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.
The syntax of try … except clause is as follows :
try:
[ program statements where exceptions might occur]
except [ exception-name]:
[code for exception handling if the exception-name error is encountered]
Program : Using try..except block
print ("Practicing for try block")
try:
numerator=50
denom=int(input("Enter the denominator"))
quotient=(numerator/denom)
print(quotient)
print ("Division performed successfully")
except ZeroDivisionError:
print ("Denominator as ZERO.... not allowed")
print(“OUTSIDE try..except block”)
However, if an exception is raised for which no handler is created by the programmer, then such an exception can be
handled by adding an except clause without specifying any exception.
This except clause should be added as the last clause of the try...except block.
If the above code is executed, and the denominator entered is 0 (zero) , the handler for ZeroDivisionError exception will
be searched.
Since it is not present, the last except clause (without any specified exception) will be executed , so the message
“OOPS.....SOME EXCEPTION RAISED” will be displayed.
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.
It is a common practice to use finally clause while working with files to ensure that the file object is closed. If used, finally
should always be placed at the end of try clause, after all except blocks and the else block.