i

Python Programming

Exceptions in Python

Exception is an event which occurs during execution of program that disrupts normal flow of  program's instructions. In general, when Python script encounters a situation that it can’t cope with it raises exception.When python script raise an exception it must either handle the exception immediately or it terminates and quits.

Handling exception

If for suspicious code that may raise an exception you can defend program by placing the suspicious code in try block. After try block include except statement followed by block of code that handles problem as elegantly possible.

Syntax

Simple syntax of try....except...else blocks −

If ExceptionaI, execute this block.

else:

   If no exception execute this block.

Here are few important points about above mentioned syntax:

•    Single try statement can multiple except statements. Useful when try block contains statements that throw different types exceptions.

•    You can also provide generic except clause which handles exception.

•   After except clause you can include else-clause. The code in else-block executes if code in the try block does not raise exception.

•    The else-block is good place for code that does not need the try block's protection.

Example

Below example opens a file, writes content in file and comes out gracefully because there is no problem at all:

Live Demo

Output:

Written content in file successfully

Example

Belowexample tries to open file where you do not have written permission and it raises an exception:

Live Demo

try:

Output:

Error: can't find file or read data

Except Clause / No Exceptions

You can use except statement with no exceptions defined as follows:

try:

   You do operations/here

Except:

   If there is exception execute this block.

else   If there is no exception execute block.

This try-except statement catches all exceptions that occur. Using this try except statement is not considered good programming practice though because it catches all exceptions but does not make programmer identify root cause of problem that occur.

Except Clause with Multiple Exceptions:

You also use the same except statement to handle multiple exceptions:

try:

   You do operations here;

excet(Exception1[, Exception2[,...ExceptinnN]]):

   If there is exception from given exception list,

Then, execute this block.

else:

   If no exception then execute the block.