"""为了是程序运行的更加稳健,我们需要对异常进行处理,避免程序崩溃退出运行。try语句可以进行异常的处理。
一个try语句可能包含多个except语句,分别来处理不同的特定异常。最多只有一个分支会被执行。一个except语句可以同时处理多个异常。
try,except语句还有一个可选的子句else语句,在没有异常产生的情况下执行。
try语句还有一个可选语句finally。它定义了无论在什么情况下都会被执行。
"""
try:
num=5/0 #运行语句,可能会有异常产生
except ZeroDivisionError:
print(str(val) + "can't be divided.")#捕获异常并进行处理异常
#except Exception2:
#handler-2 ...
else:
print(num) #没有异常发生时,运行
finally:
print("always!!")#什么情况下都会运行
raise ZeroDivisionError #使用 raise 语句抛出一个指定的异常
#使用 raise 语句抛出一个指定的异常
raise 唯一的一个参数指定了要被抛出的异常。它必须是一个异常的实例或者是异常的类(也就是 Exception 的子类)。
如果你只想知道这是否抛出了一个异常,并不想去处理它,那么一个简单的 raise 语句就可以再次把它抛出。
#你可以通过创建一个新的异常类来拥有自己的异常。
#异常类继承自 Exception 类,可以直接继承,或者间接继承,例如:
class Error(Exception):
"""Base class for exceptions in this module."""
pass
class InputError(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 = message
class TransitionError(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
#你可以通过创建一个新的异常类来拥有自己的异常。
#异常类继承自 Exception 类,可以直接继承,或者间接继承,例如:
class MyError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
raise MyError("this an error!!")
MyError Traceback (most recent call last)
<ipython-input-12-7973929b5667> in <module>
----> 1 raise MyError("this an error!!")
MyError: 'this an error!!'
网友评论