You are on page 1of 16

Introduction to Exception Handling

As a student of computer science, you know that many times while executing the
program we are getting some errors. These errors are categorized as follows:

Compile Time Errors


Compile time errors occur when the programmer is compiling a program. The Python
source code is checked for any violation of Python rules in the programming at
compile time and if anything is not as per rule, it reports an error.

As you have observed the above chart compile time errors are classified into two
categories:

1. Syntax Errors
2. Semantic Errors

Semantic Errors
Semantic Errors occur when the statement has no meaning in the program.

For example,

“Ayush is playing cricket.”

This is syntactically and semantically correct. But

“Cricket is playing Ayush.”


This is syntactically correct but semantically not.

As the rule of RHS and LHS followed in Python, the left side statement cannot be
written in the right and vice versa.

For example

a=5 #Sattement 1

b=7 #Statement 2

a+b=res #Statement 3

In the above code, Statement 3 has a semantic error because an expression never
comes to the left side of the assignment operator. It should be always on the right
side.

Logical Errors
Quite often the programmer has written the code correctly without any syntax error
or semantic error. But didn’t get the exact result that is desired. This happens
because of the programmer’s mistake where the appropriate logic is not used.

For example in place of addition, subtraction is done.

Runtime errors
Sometimes the program is correct syntactically and semantically, but when the
programmer runs the program, errors occur. Such kinds of errors are called runtime
errors.

Runtime errors are very harder to detect in the programs. These errors may stop the
program execution abnormally or crash in between or runs infinite loops.

Basically, Python terminates the program when such errors occur. But it is not
advisable that the program crashes due to unwanted things.

Exceptions
An exception is a program event that occurs during program execution and disrupts
the flow of a program. When a Python program cannot cope with a situation, it raises
an exception. An exception is a Python object that represents an error.

Some common Python exceptions are as follows:


Exception opening a file that is not present

user tries to access an element that is beyond the range


Array out of range
from list

divide by zero any number which is divided by zero – 5/0

invalid input opening a file that is not present

opening a file that does not


The user has given incorrect input
exists

What is Exception Handling in Python


The process of catching and preventing errors when they occurred is called
exception handling. It is a mechanism to overrule the exceptions using some blocks.

In other words, way of handling unexpected error during runtime is called


exception.
It is the concept of error handling when something goes wrong, tracking the error,
and calling the handling code. The following terms are used for exception handling:

Some syntax errors are also an exception. Whereas other exceptions can be generated
through code. Let us discuss some built-in exceptions in Python.
Built-in exceptions
The exceptions already defined by python are known as built-in exceptions. Python
standard library consists of large number of built-in exceptions. They are as follows:

Exception Explanation

It is raised when a built-in method or operation mismatched or


ValueError
inappropriate values are provided as input.

It is raised when the file specified in a program statement cannot


IOError
be opened.

It is raised when the user accidentally presses delete or esc key or


KeyboardInterrupt
cancels the execution.

It is raised when the specified module is not installed or not


ImportError
working.

It is raised when the end of file condition is reached without


EOFError
reading any data by input().

ZeroDivisionError It is raised when any number is having denominator zero.

It is raised when the index or subscript in a sequence is out of


IndexError
range.

NameError It is raised when a variable is accessed before declaration.

IndentationError It is raised due to incorrect indentation in the program code.

It is raised when an operator is supplied with a value of incorrect


TypeError
data type.

It is raised when the result of a calculation exceeds the maximum


OverFlowError
limit for numeric data type.
User-defined exceptions
The exception created by the programmer according to the requirement of the
program is called user-defined exceptions.

The user defined-exception can be created using two methods:

1. raise statement
2. assert statement

raise statement
It is used to throw an exception. The syntax is as follows:

raise exception-name[(optional argument)]

The optional argument is a string passed to the exception, that displays the
message. The exception may be user-defined or built-in.

Example:

d={'A':9,'B':10}
k=input("Enter key to search:")

if k in d.keys():

print("Key found in dict...")

else:

raise KeyError("Key not present in dict...")

Output:

assert statement
An assert statement in Python is used to check a condition in the program code. If
the result after evaluation is false, then the exception is raised.

This statement is generally used at the beginning of the function or after a function
call to check for valid input. The syntax for the 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.

Example:

def odd_even(n):

assert (n%2==0),"Even Number..."

print("Odd Number")

odd_even(6)
odd_even(5)

Process of exception handling

Step 1: The exception object is created by a Python interpreter that contains


information related to the error such as type, file name, and position where an error
has occurred.

Step 2: The object is handed over to the runtime system to find an appropriate code
to handle exceptions. This process is called throwing an exception.

Step 3: The runtime system searches for a block of code known as an exception
handler that handles the raised error. First, it searches for the method by which the
error has occurred. If not found then it search method from which this method is
called. This process continues till the exception handler is found. When it found a
handler it will be executed. This process is known as catching.

Step 4: Finally the program gets terminated

Catching Exceptions
Catching exceptions refers to the execution of code that handles particular
exceptions. Any exception caught through try block and handled through except
block.
try and except block
The try block contains the actual codes that need to be executed. Every try block is
followed by except block. The exception handling code is written inside the except
block.

In the execution of the program, if an exception is raised the try block execution is
stopped and the control is shifted to except block. The syntax of try and except is as
follows:

try:

program statement in which exception may occur

except [exception_name]:

exception handler code

Example 1 : NameError Exception

try:

print(x)

except NameError:

print("Varibale is not defined...")

Output:

Example 2: ValueError Exception

try:

a = int(input("Enter your age: "))


except ValueError:

#Print message for ValueError

print("Invalid input:Enter numbers only")

Output:

Example 3: ImportError

try:

import Datetime

print("Module")

except ImportError:

print("Invalid module Can't import")

Example 4: ZeroDivisionError

try:

c=5/0

except ZeroDivisionError:

print("You cannot divide")

Example 5: IndexError

l=[11,45,67,89]
try:
print(l[5])
except IndexError:
print("Index not found")
Example 6: TypeError

try:

a=5

print(a+'b')

except TypeError:

print("Invalid Datatypes")

You can also raise exceptions without exception names in except block. Observe
this code:

print ("Handling multiple exceptions")

try:

a=10 / 0

except:

print("Exception Raised...")

Handling multiple exceptions


Multiple exceptions can be handled together using multiple exceptions with multiple
exception handlers. There are two ways to handle multiple exceptions.

1. Writing multiple exception handlers together


2. Writing multiple exception handlers with separate except blocks
Writing multiple exception handlers together
The multiple exception handlers can be written within one except block. When the
first exception is raised it will stop execution and evaluate the first except block.

Example:

try:
result = 10 / 0
result = 10 +'d'
except ZeroDivisionError, TypeError as e:
print("Error occurred:", e)

In the above code, the ZeroDivisionError exception is raised in the first line, and the
relevant message is generated. If the first exception is not raised then it will jump to
another exception i.e. TypeError.

Writing multiple exception handlers with separate


except blocks
Multiple except blocks are required for this method. Observe the example:

try:

result = 10 / 0

result = 10 + 'd'

except ZeroDivisionError as e:

print("Error occurred:", e)

except TypeError as e1:

print("Error occurred:",e1)
Use of else clause in exception handling
in Python
Now you are familiar with the process of exception handling, where except block will
be executed if any exception is raised in the try block. But when no error is reported,
then no except block will be executed. In this scenario else block comes into play a
role.

The else block in exception handling in Python will be executed in a similar manner
as it is executed in if…else, while..else etc. Observe this code:

print ("Handling multiple exceptions")

try:

n1=int(input("Enter number1:"))

n2=int(input("Enter number2:"))

res=n1+n2

except ValueError:

print("Enter integers only...")

else:

print("The result is:",res)

Finally Clause
The finally clause ends the exception-handling process. It bottom last clause after
handling all except clauses including else block. The finally clause always executes
at the end. Just have a look at the following:

The finally clause ends the exception-handling process. It bottom last clause after
handling all except clauses including else block. The finally clause always executes
at the end. Just have a look at the following:
print ("Handling multiple exceptions")

try:

n1=int(input("Enter number1:"))

n2=int(input("Enter number2:"))

res=n1+n2

except ValueError:

print("Enter integers only...")

else:

print("No exception raised...")

print("The result is:",res)

finally:

print("You have done it!!! Bye Bye")


If sometimes any exception which is not caught in exception handler, in this scenario
too the finally clause will execute first and the exception is re-raised. Just observe
this code:

print ("Handling multiple exceptions")

try:

n1=int(input("Enter number1:"))

n2=int(input("Enter number2:"))

res=n1/n2

except ZeroDivisionError:

print("Enter integers only...")

else:

print("No exception raised...")

print("The result is:",res)

finally:

print("You have done it!!! Bye Bye")

Output:
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.

Some MCQ questions:

1. The process of creating an exception object and handing it over to the


runtime system is called …………. an exception
1. Growing
2. Throwing
3. Executing
4. Handling

2. The syntax of raise statement is:


1. raise exception-name ((optional argument))
2. raise exception-name {(optional argument)}
3. raise exception-name [(optional argument)]
4. None of the above

3. The statements inside the finally block are always executed regardless
of whether an exception occurred in the try block or not.
1. True
2. False
3. Depend on code
4. None of the above

4. An exception is caught in the …….. block and handles in ……….. block.


1. except, try
2. try, except
3. EOF, Error
4. program, compile

5. Syntax errors are also handled as exceptions


1. False
2. True
3. Some times
4. None of the above

6. An exception is a Python object that represents an ………….


1. Logic
2. Expression
3. Error
4. Module
7. Exception handling can be done for:
1. user-defined
2. built-in
3. Both 1 and 2
4. None

8. Commonly Built in exception:


1. Value Error
2. Import Error
3. Type Error
4. All the above

9. An exception is a Python ………… that represents an error.


1. Class
2. Method
3. Object
4. All the above

You might also like