Catch more than one exceptions

Catch more than one exceptions

If there are more than one type of exceptions throwed out of the code we can choose to handle each exception type separately.

The basic logic to handle multiple exceptions together is


try:// ww  w. j a va2  s.  c  o m
   code to throw exception type 1
   code to throw exception type 2
   code to throw exception type 3
except (ExceptionType1, ExceptionType2,ExceptionType3):
   handler logic statements

Syntax to handler exception one by one.


try://from   w  w  w  . j a  v a2s .  co  m
   code to throw exception type 1
   code to throw exception type 2
   code to throw exception type 3
except ExceptionType1:
   code to handle ExceptionType1
except ExceptionType2:
   code to handle ExceptionType2
except ExceptionType3:
   code to handle ExceptionType3

#   www  . j a  va 2s .  c o m
try: 
    x = input('Enter the first number: ') 
    y = input('Enter the second number: ') 
    print x/y 
except (ZeroDivisionError, TypeError): 
    print 'Your numbers were bogus...' 
    


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!" 
except TypeError: 
    print "That wasn't a number, was it?" 
    
    

Catch all

If you do want to catch all exceptions in a piece of code, you can simply omit the exception class from the except clause:


try: # w w w  . ja  va  2s .  co  m
    x = input('Enter the first number: ') 
    y = input('Enter the second number: ') 
    print x/y 
except: 
    print 'Something wrong happened...' 




















Home »
  Python »
    Advanced Features »




Exception Handling
File
Module