Saturday 5 December 2015

Python: Handling Exceptions

Python provide keywords try, except to handle exceptions.


test.py
while True:
 try:
  x = int(input("Enter input "))
  print(x)
  break;
 except ValueError:
  print("Please enter valid number")

$ python3 test.py 
Enter input an
Please enter valid number
Enter input ana
Please enter valid number
Enter input ptr
Please enter valid number
Enter input 10
10

How try and except block work?
The statements in try block executed first. If no exception occurs, the except clauses are skipped and execution of the try statement is finished. If any exception occurs during the execution of try block, the rest of the try clause is skipped.

‘try’ block followed by number of except clauses, if exception thrown in try cause matches to any exception followed by except clause, then particular except clause is executed.

If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops by throwing exception message.

Try block can be followed by multiple except clauses

test.py
while True:
 try:
  x = int(input("Enter divisor "))
  y = int(input("Enter dividend "))
  print(x/y)
  break;
 except ValueError:
  print("Please enter valid number")
 except ZeroDivisionError:
  print("y should be non zero")

$ python3 test.py 
Enter divisor 2
Enter dividend 0
y should be non zero
Enter divisor 4
Enter dividend 0
y should be non zero
Enter divisor 4
Enter dividend 2
2.0


Handling multiple exceptions in single except clause
An except clause can catch more than one exception. For example ‘except (ValueError, ZeroDivisionError)’ can handle both ValueError and ZeroDivisionError.

test.py
while True:
 try:
  x = int(input("Enter divisor "))
  y = int(input("Enter dividend "))
  print(x/y)
  break;
 except (ValueError, ZeroDivisionError):
  print("Please enter valid number (or) y should be greater than 0")

 $ python3 test.py 
Enter divisor 2
Enter dividend 0
Please enter valid number (or) y should be greater than 0
Enter divisor aa
Please enter valid number (or) y should be greater than 0
Enter divisor 2
Enter dividend 4
0.5


Last except clause can omit exception name. It is used as global exception handler.

test.py
while True:
 try:
  tempList=[]
  print(tempList[10])
  break
 except ValueError:
  print("Please enter valid number")
 except ZeroDivisionError:
  print("y should be non zero")
 except Exception as inst:
  print("Global handler", inst)
  break

$ python3 test.py 
Global handler list index out of range


try…except…else clause
‘try…except’ statement can have optional else clause, it is followed by except clause. If try block doesn’t throw any exception, else clause will be executed.

test.py
while True:
 try:
  x = int(input("Enter divisor "))
  y = int(input("Enter dividend "))
  print(x/y)
 except ValueError:
  print("Please enter valid number")
 except ZeroDivisionError:
  print("y should be non zero")
 else:
  print("Program executed successfully")
  break

$ python3 test.py 
Enter divisor 4
Enter dividend 2
2.0
Program executed successfully


Exception argument
Whenever an exception occurs, it is associated with a variable called exception argument.

test.py
while True:
 try:
  x = int(input("Enter divisor "))
  y = int(input("Enter dividend "))
  print(x/y)
 except ValueError as inst:
  print(inst)
 except ZeroDivisionError as inst:
  print(inst)
 else:
  print("Program executed successfully")
  break

$ python3 test.py 
Enter divisor qwerty
invalid literal for int() with base 10: 'qwerty'
Enter divisor 4
Enter dividend 0
division by zero
Enter divisor 2
Enter dividend 4
0.5
Program executed successfully


The except clause can specify a variable after the exception name. The variable is bound to an exception instance with the arguments stored in instance.args.

test.py
while True:
 try:
  x = int(input("Enter divisor "))
  y = int(input("Enter dividend "))
  
  if y==0:
   raise Exception(x, y)
  print("x/y = ",x/y)
  break
 except Exception as inst:
  arg1, arg2 = inst.args
  print("arg1=", arg1)
  print("arg2=", arg2)

$ python3 test.py 
Enter divisor 2
Enter dividend 0
arg1= 2
arg2= 0
Enter divisor 2
Enter dividend 4
x/y =  0.5


If an exception has arguments associated with it, those are printed as last part of the exception message.

test.py
while True:
 try:
  x = int(input("Enter divisor "))
  y = int(input("Enter dividend "))
  
  if y==0:
   raise Exception(x, y)
  print("x/y = ",x/y)
  break
 except Exception as inst:
  print(inst)

$ python3 test.py 
Enter divisor 2
Enter dividend 0
(2, 0)
Enter divisor 2
Enter dividend 4
x/y =  0.5












Previous                                                 Next                                                 Home

No comments:

Post a Comment