Introduction to exceptions in python, python Introduction
Each exception is a type of instance, which can be thrown and captured in many ways, so that the program can catch and handle errors.
>>> 1/0Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> 1/0ZeroDivisionError: integer division or modulo by zero
Exception Handling
You can use the try/try t statement to catch exceptions.
>>> def inputnum(): x=input('Enter the first number: ') y=input('Enter the first number: ') try: print x/y except ZeroDivisionError: print "The second number can't be zero" >>> inputnum()Enter the first number: 10Enter the first number: 0The second number can't be zero
Raise trigger exception
>>> class Muff: muffled=False def calc(self,expr): try: return eval(expr) except ZeroDivisionError: if self.muffled: print 'Division by zero is illegal' else: raise >>> c=Muff()>>> c.calc(10/2)Traceback (most recent call last): File "<pyshell#33>", line 1, in <module> c.calc(10/2) File "<pyshell#31>", line 5, in calc return eval(expr)TypeError: eval() arg 1 must be a string or code object>>> c.calc('10/2')5>>> c.calc('1/0')Traceback (most recent call last): File "<pyshell#35>", line 1, in <module> c.calc('1/0') File "<pyshell#31>", line 5, in calc return eval(expr) File "<string>", line 1, in <module>ZeroDivisionError: integer division or modulo by zero>>> c.muffled=True>>> c.calc('1/0')Division by zero is illegal
Multiple exception types
try: x=input('Enter the first number:') y=input('Enter the seconed number:') print x/yexcept ZeroDivisionError: print "The second number can't be zero!"except TypeError: print "That wasn't a number,was it?"
Capture multiple exceptions at the same time
try: x=input('Enter the first number:') y=input('Enter the seconed number:') print x/yexcept(ZeroDivisionError,TypeError,NameError): print 'Your numbers were bogus...'
Object capturing
try: x=input('Enter the first number:') y=input('Enter the seconed number:') print x/yexcept(ZeroDivisionError,TypeError),e: print e Enter the first number:1Enter the seconed number:0integer division or modulo by zero
Catch all exceptions
try: x=input('Enter the first number:') y=input('Enter the seconed number:') print x/yexcept: print 'something wrong happened...' Enter the first number:something wrong happened...