Catching Exceptions : try « Statement « Python Tutorial






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!"

class MyCalc:
   muffled = 0
   def calc(self, expr):
      try:
        return eval(expr)
      except ZeroDivisionError:
       if self.muffled:
          print 'Division by zero is illegal'
      else:
          raise 

calculator = MyCalc()
calculator.calc('10/2')
calculator.calc('10/0') # No muffling

calculator.muffled = 1 
calculator.calc('10/0')








3.8.try
3.8.1.try statement encloses pieces of code where one or more known exceptions may occur
3.8.2.Catching Exceptions
3.8.3.Catching Two Exceptions with One Block
3.8.4.Catching the Object
3.8.5.A Real Catch all
3.8.6.Have a block of code that is executed unless something bad happens;
3.8.7.try-finally Statement
3.8.8.The else Clauses: provide a path to execute if no exceptions occur during the try block
3.8.9.Catch Keyboard interrupt exception
3.8.10.Multiple except Clauses
3.8.11.Except two exceptions
3.8.12.Blank except Clauses
3.8.13.traceback object can print out information about the exception
3.8.14.Exception Arguments
3.8.15.get an exception's argument