每個異常都是一些類別的實例,這些實例可以被引發,並且可以用很多種方法進行捕捉,使得程式可以捉住錯誤並且對其進行處理
>>> 1/0 Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> 1/0 ZeropisionError: integer pision or modulo by zero
捕捉異常可以使用try/except語句。
>>> 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: 10 Enter the first number: 0 The second number can't be zero
raise 觸發異常
>>> 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') >>> 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 pision or modulo by zero >>> c.muffled=True >>> c.calc('1/0') Division by zero is illegal
多種例外類型
try: x=input('Enter the first number:') y=input('Enter the seconed number:') print x/y except ZeroDivisionError: print "The second number can't be zero!" except TypeError: print "That wasn't a number,was it?"
同時 捕捉多個例外
try: x=input('Enter the first number:') y=input('Enter the seconed number:') print x/y except(ZeroDivisionError,TypeError,NameError): print 'Your numbers were bogus...'
捕捉物件
try: x=input('Enter the first number:') y=input('Enter the seconed number:') print x/y except(ZeroDivisionError,TypeError),e: print e Enter the first number:1 Enter the seconed number:0 integer pision or modulo by zero
# 捕捉所有例外
try: x=input('Enter the first number:') y=input('Enter the seconed number:') print x/y except: print 'something wrong happened...' Enter the first number: something wrong happened...
以上是關於python中異常的詳細說明的詳細內容。更多資訊請關注PHP中文網其他相關文章!