Python Exception Handling Tutorial

Topic:Python Exception Handling Tutorial

Python Exception Handling Tutorial with Examples Programs

Exception handling is one of the most important feature of any modern programming language. Therefore, Python programming language provides the Exception handling features. Exception handling will allow us to handle the errors caused by exceptions.

What is Exception Handling?

Exception Handling is the process of handling expected run time errors in your programs gracefully.
Python Exception Handling Tutorial With Example Programs

What is Exception

An exception is any run time error in your program that should be handled by the programmer. Errors detected at run tine are called exceptions. For example, if any statement in your Python program tries to
divide a number by zero, a Divide by zero exception will occure:

x = 100
y = 0
z = x /y   # divide by zero
print(" I will not be executed, if exception occurs in above statement  z = x / y")
  • The exception / run time error ‘Divide by Zero; will occure and the program will be terminated.
  • A default error message will be displayed

What Happens If We Do Not Handle Exceptions?

If we do not handle the expected exception or exceptins in the program, the program will be terminated on occurrence of any exception
and the statements after the erroneous statement will not be executed
A default system generated message is shown to the user

Example of Default Exception Handling in Python

Normal Flow of Python Program Execution

If there is no error in the program, all the statements in the Python program are executed one by one in the given sequence
and the the output is shown on the screen as shown in the following case:

x = 100
y = 10
z = x /y   # divide by zero
print("Answer  = ", z)
Output:

Answer =  10.0

Default Exception Handler

But if there is an error due to any statement and we do not handle this, then:

  • A default exception handler is started
  • The program displays a default error message
  • Due to this error, the program is terminated.
  • Hence, no statements after the erroneous statement are executed.

Example:

x = 100
y = 0
z = x /y   # Divide by zero exception because y = 0
print("Answer = ",z)  # will not be executed, hence no output

As we see, the line number three in the above Python program will generate a run time error, normally called A divide by Zero Error.
This is because the value of y = 0, hence x / y will cause divide by zero error.

When we try to execute the above Python Program, the error message due to line number 3, will be as follows:

Traceback (most recent call last):
  File "C:/Users/h/AppData/Local/Programs/Python/Python37-32/exception1.py", line 3, in <module>
    z = x /y   # divide by zero
ZeroDivisionError: division by zero

How To Use ExceptionHandling Features in Python?

We use try-except blocks to handle exceptions in Python code.

What is Python try Block?

Python try-block is a set of statement under try: which may generate any kind of exception. Therefore, we must place any statements with the possibility of
error in try-block.

Syntax of Python try Block:

try:
    statement1
    statement2
    statement3
    ...    

Example of Python try Block:

try:
    z = x /y   # Divide by zero exception because y = 0
    print("Answer = ",z)  # will not be executed, hence no output

What is Python except Block

the Python except block will contain the basic exception handling code that will handle any error occured in any statement of the try-block.

Syntax of Python except Block:
except ExceptionType:
    statement1
    statement2
    statement3
    ...    
Example of Python except Block:
except ZeroDivisionError:
    print("Divide by zero error, Please do not assign zero to variable 'y'")

The Example of Python try-except blocks

we will write any statements with the possibility of error in the try block. A set of error handling statements will be kept in the except-block.
The except block will be executed if any exception occurs in try block. the except block is placed after the try block.

x = 100
y = 0
try:
    z = x /y   # Divide by zero exception because y = 0
    print("Answer = ",z)  # will not be executed, hence no output
except ZeroDivisionError:
    print("Divide by zero error, Please do not assign zero to variable 'y'")

print("The End")  
Output:

Divide by zero error, Please do not assign zero to variable 'y'
The End

What is else Clause?

We may use try-except-else blocks in the same sequence. As we know that try block will have the code to be monitored for any exceptions. Whereas, the except block will contain the necessary Python statements to handle the excpetion.

An else clause or else block is used to write the Python statements that will execute only if there occurs no exception at all.

Example of Using try except else blocks

Here we consider a Python program with an exception, therefore, else block will not be executed:

x = 100
y = 0
try:
    z = x /y   # Divide by zero exception because y = 0
    print("Answer = ",z)  # will not be executed, hence no output
except ZeroDivisionError:
    print("Divide by zero error, Please do not assign zero to variable 'y'")
else:
    print("Program ended successfully without exception")

print("Last statement")
Output:
Divide by zero error, Please do not assign zero to variable 'y'
Last statement

Now we consider a Python program with no exception, therefore else block will be executed:

x = 100
y = 10
try:
    z = x /y   
    print("Answer = ",z)  
except ZeroDivisionError:
    print("Divide by zero error, Please do not assign zero to variable 'y'")
else:
    print("I am in else Block, Program ended successfully without exception")

print("Last statement")
Output:
Answer =  10.0
I am in else Block, Program ended successfully without exception
Last statement

What is the Use of finally Block?

The statements in the finally clause / block will run every time no matter exception occurs or not.
Let us consider a Python program using finally block with no exception:

x = 100
y = 10
try:
    z = x /y   
    print("Answer = ",z)  
except ZeroDivisionError:
    print("Divide by zero error, Please do not assign zero to variable 'y'")
else:
    print("I am in else Block, Program ended successfully without exception")
finally:
    print("In finally block, will execute always, exception occurs or not")
Output:
Answer =  10.0
I am in else Block, Program ended successfully without exception
In finally block, will execute always, exception occurs or not

Now we will consider a Python program using finally block with an exception at run time:

x = 100
y = 0
try:
    z = x /y   
    print("Answer = ",z)  
except ZeroDivisionError:
    print("Divide by zero error, Please do not assign zero to variable 'y'")
else:
    print("I am in else Block, Program ended successfully without exception")
finally:
    print("In finally block, will execute always, exception occurs or not")
Output:
Divide by zero error, Please do not assign zero to variable 'y'
In finally block, will execute always, exception occurs or not

Catching Multiple Exceptions

Using Multiple except blocks for a try block

We can catch multiple exceptions using multiple except blocks with a try block:

syntax:
try:
    statements
except Exceptiontype1:
    statements1
except Exceptiontype2:
    statements2
else:
    statements else

Let us examine a Python program that uses multiple except bloacks with a try block.

x = 100
y = 10
s = "string"
try:
    z = x /y   
    print("Answer of division= ",z)
    z = x + s
    print("Answer of  addition= ",z)
except ZeroDivisionError:
    print("Divide by zero error, Please do not assign zero to variable 'y'")
except TypeError:
    print("Type mismatch for this operation, cannot add int number to a string")
else:
    print("Thanks")
Output:
Answer of division=  10.0
Type mismatch for this operation, cannot add int number to a string

Python Exception Handling Tutorial


Leave a Reply

Your email address will not be published.