0% found this document useful (0 votes)
124 views27 pages

12 Exception

The document discusses exception handling in Python. It defines syntax errors as errors that occur due to not following language rules when writing code. Exceptions occur during execution, such as trying to open a non-existent file. Built-in exceptions are predefined in Python for common errors. Exceptions are raised when errors occur, and exception handlers execute code to handle specific exceptions. Try and except blocks are used to catch exceptions, with except clauses handling different exception types. Finally blocks always execute after try and except regardless of exceptions.

Uploaded by

krishthefish
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
124 views27 pages

12 Exception

The document discusses exception handling in Python. It defines syntax errors as errors that occur due to not following language rules when writing code. Exceptions occur during execution, such as trying to open a non-existent file. Built-in exceptions are predefined in Python for common errors. Exceptions are raised when errors occur, and exception handlers execute code to handle specific exceptions. Try and except blocks are used to catch exceptions, with except clauses handling different exception types. Finally blocks always execute after try and except regardless of exceptions.

Uploaded by

krishthefish
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 27

Exception Handling

Python
1.2 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.
So, a syntax error is reported by the Python
interpreter giving a brief explanation about the
error and a suggestion to rectify it.
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.
An exception is a Python object that represents an
error. When an error occurs during the execution of a
program, an exception is said to have been raised.
1.4 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. 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.
1.5 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.
1.5.1 The raise Statement
 The raise statement can be used to throw an exception. The syntax of raise statement is:raise
exception-name[(optional argument)]The argument is generally a string that is
displayed when the exception is raised. For example, when an exception is raised as shown in
Figure 1.5, the message “OOPS : An Exception has occurred” is displayed along with a brief
description of the error.
In Figure 1.6, since the value of variable length is greater than the length of the
list numbers, an IndexError exception will be raised. The statement
following the raise statement will not be executed. So the message “NO
EXECUTION” will not be displayed in this case.
In addition to the error message displayed, Python also displays a stack
Traceback. This is a structured block of text that contains information about the
sequence of function calls that have been made in the branch of execution of
code in which the exception was raised.
1.5.2 The assert Statement
An assert statement in Python is used to test an expression in the
program code. If the result after testing comes false, then the exception
is raised. This statement is generally used in the beginning of the
function or after a function call to check for valid input.
The syntax for assert statement is:
assert Expression[,arguments]
On encountering an assert statement, Python evaluates the expression
given immediately after the assert keyword. If this expression is false,
an AssertionError exception is raised which can be handled like any
other exception. Consider the code given in Program 1-1.
Use of assert statement
print("use of assert statement")
def negativecheck(number):
assert(number>=0), "OOPS... Negative Number"
print(number*number)
print (negativecheck(100))
print (negativecheck(-350))
1.6 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.
1.6.1 Need for Exception Handling

 It is a useful technique that helps in capturing runtime errors and handling them
so as to avoid the program getting crashed. Following are some of the important
points regarding exceptions and their handling:
◦ Python categorises exceptions into distinct types so that specific exception handlers (code
to handle that particular exception) can be created for each type.
◦ 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.
Process of Handling Exception
Throwing an exception
 When an error occurs, Python interpreter creates an object called the
exception object.
 This object contains information about the error like its type, file name
and position in the program where the error has occurred.
 The object is handed over to the runtime system so that it can find an
appropriate code to handle this particular exception.
 This process of creating an exception object and handing it over to the
runtime system is called throwing an exception.
 Rest of the statements are not executed after encountering the
exception.
 catching the exception
 The runtime system searches the entire program for a block of code, called the exception handler
that can handle the raised exception.
 It first searches for the method in which the error has occurred and the exception has been raised.
 If not found, then it searches the method from which this method (in which exception was raised)
was called.
 This hierarchical search in reverse order continues till the exception handler is found.
 This entire list of methods is known as call stack. When a suitable handler is found in the call
stack, it is executed by the runtime process.

 This process of executing a suitable handler is known as catching the exception. If the runtime
system is not able to find an appropriate exception after searching all the methods in the call
stack, then the program execution stops.
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. 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]
Using try…except block

print ("Practicing for try block")


try:
numerator=50
denom=int(input("Enter the denominator"))
quotient=(numerator/denom)
print ("Division performed successfully")
except ZeroDivisionError:
print ("Denominator as ZERO.... not allowed")
print(“OUTSIDE try..except block”)
the ZeroDivisionError exception is handled. If the user enters any non-zero
value as denominator, the quotient will be displayed along with the message
“Division performed successfully.
The except clause will be skipped in this case. So, the next statement after the
try..except block is executed and the message “OUTSIDE try.. except block”
is displayed.
However, if the user enters the value of denom as zero (0), then the execution
of the try block will stop. The control will shift to the except block and the
message “Denominator as Zero…. not allowed” will be displayed.
Thereafter , the statement following the try..except block is executed and the
message “OUTSIDE try..except block” is displayed in this case also.
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.

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.
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,
the statements inside the else clause will be
executed.
Use of else clause

print ("Handling exception using try...except...else")


try:
numerator=50
denom=int(input("Enter the denominator: "))
quotient=(numerator/denom)
print ("Division performed successfully")
except ZeroDivisionError:
print ("Denominator as ZERO is not allowed")
except ValueError:
print ("Only INTEGERS should be entered")
else:
print ("The result of division operation is ", quotient)
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.
Use of finally clause

print ("Handling exception using try...except...else")


try:
numerator=50
denom=int(input("Enter the denominator: "))
quotient=(numerator/denom)
print ("Division performed successfully")
except ZeroDivisionError:
print ("Denominator as ZERO is not allowed")
except ValueError:
print ("Only INTEGERS should be entered")
else:
print ("The result of division operation is ", quotient)

finally:
print ("OVER AND OUT")
Recovering and continuing with finally clause

If an error has been detected in the try block and the exception has been
thrown, the appropriate except block will be executed to handle the error.
But if the exception is not handled by any of the except clauses, then it is
re-raised after the execution of the finally block.
For example, Program 1.4 contains only the except block for
ZeroDivisionError.
If any other type of error occurs for which there is no handler code
(except clause) defined, then also the finally clause will be executed first.
Consider the code given in Program 1-7 to understand these concepts.
Recovering through finally clause
print (" Practicing for try block")
try:
numerator=50
denom=int(input("Enter the denominator"))
quotient=(numerator/denom)
print ("Division performed successfully")
except ZeroDivisionError:
print ("Denominator as ZERO is not allowed")
else:
print ("The result of division operation is ", quotient)
finally:
print ("OVER AND OUT")
 While executing the above code, if we enter a non-numeric data as input, the
finally block will be executed. So, the message “OVER AND OUT” will be
displayed. Thereafter the exception for which handler is not present will be
re-raised.

 After execution of finally block, Python transfers the control to a previously


entered try or to the next higher level default exception handler. In such a
case, the statements following the finally block is executed. That is, unlike
except, execution of the finally clause does not terminate the exception.
Rather, the exception continues to be raised after execution of finally.
 Tosummarise, we put a piece of code where there are
possibilities of errors or exceptions to occur inside a try
block. Inside each except clause we define handler
codes to handle the matching exception raised in the try
block. The optional else 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.

You might also like