How to catch an exception

Catch exception

In case of an exception we can catch the exception and provide logic of to handle the exception.

The basic syntax of exception handling is


try
   some code to raise exception
except ExceptionClassName
   exception handler statements

try statement encloses pieces of code where one or more known exceptions may occur


try:#  w w  w .ja  v  a  2  s  . c  o  m
    1/0
except ZeroDivisionError:
    print "Can't divide anything by zero."
    

   
try: 
    x = input('Enter the first number: ') 
    y = input('Enter the second number: ') 
    print x/y 
except ZeroDivisionError: 
    print "The second number can't be zero!" 

The code above generates the following result.

Catching the exception object

If you want access to the exception itself in an except clause, you can use two arguments.


try: # from  ww w. j ava2s  . co  m
    x = input('Enter the first number: ') 
    y = input('Enter the second number: ') 
    print x/y 
except (ZeroDivisionError, TypeError), e: 
    print e 

The code above generates the following result.





















Home »
  Python »
    Advanced Features »




Exception Handling
File
Module