0% found this document useful (0 votes)
4 views

Chapter 1 Exception Handling

Uploaded by

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

Chapter 1 Exception Handling

Uploaded by

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

Chapter 1

EXCEPTION HANDLING

1.1 Introduction
In Python, exceptions are errors that get triggered automatically.
However, exceptions can be forcefully triggered and handled through
program code.

1.2 Syntax Error


Syntax errors are detected when we have not followed the rules of
the particular programming language. These errors are also known as
parsing errors. On encountering a syntax error, the interpreter does not
execute the program.

1.3 Exceptions
It is an error that occurs during the execution of the program,
which disrupts the normal flow of the program.
Ex: Trying to open a file that does not exist, division by zero and so on.

1.4 Built-in exceptions


Exceptions which are pre-defined in the interpreter are called built-in
exceptions.
Python’s standard library is an extensive collection of built-in
exceptions that deals with the commonly occurring exceptions.
Ex:

SL. NameoftheBuilt- Explanation


No inException

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 module definition
is not found.
6 EOFError It is raised when the end of file condition is
reached without reading any data by input().

1
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.

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.

1.5.1 The raise Statements


The raise statement can be used to throw an exception.
Syntax:
raise exception-name[(optional argument)]
The argument is generally a string that is displayed when the exception is
raised.
Ex:
raise excep(“ Exception raised”)
When an exception is raised, the message “Exception raised” is displayed
along with a brief description of the error.

1.5.2 The assert Statements:


It is used to test an expression in the program code. If the result is
false, then the exception is raised.

2
Syntax:
assert Expression[,arguments]
On encountering an assert statement, Python evaluates the
expression. If this expression is false, an AssertionError exception is
raised which can be handled like any other exception.
Ex: assert(number>=0),"OOPS...Negative Number"

1.6 Handling Exceptions


Exceptions are handled by the programmer by writing 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 (Features/Advantages)


➢ It is a useful technique that helps in capturing runtime errors and
handling them so as to avoid the program getting crashed.
➢ Python categorises exceptions into distinct types so that specific
exception handlers can be created for each type.
➢ Exception handlers separate the main logic of the program from the
error detection and correction code.
➢ 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.

1.6.2 Process of Exception Handling


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. When an exception occurs while executing a particular program
statement, the control jumps to an exception handler, abandoning execution
of the remaining program statements.
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
3
exception after searching all the methods in the call stack, then the
program execution stops.

1.6.3 Catching Exceptions


An exception is said to be caught when a code that is designed to
handle a particular exception is executed. The code that may cause an error is
placed inside a try block, and the error-handling code is written in the except
block. If an exception occurs during execution, the remaining code inside the try
block is skipped, and control immediately moves to the corresponding except block.
Syntax:
try:
[program statements where exceptions might occur]
except [exception-name]:
[code for exception handling ]
4
Ex:
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”)

For handling multiple errors, we can have multiple except blocks for a
single try block.
Ex:
try:
numerator=50
denom=int(input("Enter the denominator:"))
print (numerator/denom)
print("Division performed successfully")
except ZeroDivisionError:
print("Denominator as ZERO is not allowed")
except ValueError:
print("Only INTEGERS should be entered")
except:

5
print("OOPS.....SOME EXCEPTION RAISED")
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.
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.

1.6.4 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.
Ex:
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)

1.7 Finally clause


The try statement 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.
Ex:
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:
6
print("Only INTEGERS should be entered")
else:
print("The result of division operation is", quotient)
finally:
print("OVER AND OUT")
In the above program, the message “OVER AND OUT” will be displayed
irrespective of whether an exception is raised or not.

1.7.1 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.
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. There after the exception for which handler is not present will
be re-raised.
Summary:
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