>>>10* (1/0)Traceback (most recent call last): File "<stdin>", line 1,in<module>ZeroDivisionError: division by zero>>>4+ spam*3Traceback (most recent call last): File "<stdin>", line 1,in<module>NameError: name 'spam'isnot defined>>>'2'+2Traceback (most recent call last): File "<stdin>", line 1,in<module>TypeError: Can't convert 'int' object to str implicitly
异常处理
程序发生了异常之后该怎么处理呢?
我们可以使用try except 语句来捕获特定的异常。
>>>whileTrue:... try:... x =int(input("Please enter a number: "))... break... exceptValueError:... print("Oops! That was no valid number. Try again...")...
import sys
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except OSError as err:
print("OS error: {0}".format(err))
except ValueError:
print("Could not convert data to an integer.")
except:
print("Unexpected error:", sys.exc_info()[0])
raise
>>>deffunc():... raiseIOError...>>>try:... func()... exceptIOErroras exc:... raiseRuntimeError('Failed to open database')from exc...Traceback (most recent call last): File "<stdin>", line 2,in<module> File "<stdin>", line 2,in funcOSErrorThe above exception was the direct cause of the following exception:Traceback (most recent call last): File "<stdin>", line 4,in<module>RuntimeError: Failed to open database
try:open('database.sqlite')exceptIOError:raiseRuntimeErrorfromNoneTraceback (most recent call last): File "<stdin>", line 4,in<module>RuntimeError
自定义异常
用户可以继承 Exception 来实现自定义的异常,我们看一些自定义异常的例子:
classError(Exception):"""Base class for exceptions in this module."""passclassInputError(Error):"""Exception raised for errors in the input. Attributes: expression -- input expression in which the error occurred message -- explanation of the error """def__init__(self,expression,message): self.expression = expression self.message = messageclassTransitionError(Error):"""Raised when an operation attempts a state transition that's not allowed. Attributes: previous -- state at beginning of transition next -- attempted new state message -- explanation of why the specific transition is not allowed """def__init__(self,previous,next,message): self.previous = previous self.next =next self.message = message