python 的处理错误的方式:
1> 断言
assert condition
相当于
if not condition:
crash program
断言设置的目的就是因为与其让程序晚点崩溃,不如直接设置错误情况,让它直接崩溃
>>> age = -1
>>> assert 0 < age < 100
AssertionError
2> raise语句
通过raise可以引发异常
>>> raise Exception
Traceback (most recent call last):
File "<pyshell#173>", line 1, in <module>
raise Exception
Exception
>>> raise Exception('overload')
Traceback (most recent call last):
File "<pyshell#174>", line 1, in <module>
raise Exception('overload')
Exception: overload
此外常见的内建异常类有:
Exception 所有异常的基类
AttributeError 特性应用或赋值失败时引发
IOError 试图打开不存在的文件时引发
IndexError 在使用序列中不存在的索引时引发
KeyError 在使用映射不存在的键时引发
NameError 在找不到名字(变量)时引发
SyntaxError 在代码为错误形式时引发
TypeError 在内建操作或者函数应用于错误类型的对象是引发
ValueError 在内建操作或者函数应用于正确类型的对象,但是该对象使用不合适的值时引发
ZeroDivisionError 在除法或者摸除操作的第二个参数为0时引发
3> 捕捉异常
try:
x = input()
y = input()
print(x/y)
except ZeroDivisionError:
print("Division by Zero")
类似这样try/except形式就是来捕捉可能发生的异常错误,一旦出现ZeroDivisionError错误信息,则运行except ZeroDivisionError之后的代码
通过多个except来捕捉不同错误信息
def calc(expr):
try:
return eval(expr)
except ZeroDivisionError:
print("Divison by zero")
except TypeError:
print('This is not a number?')
一个块捕捉多个错误信息
def calc(expr):
try:
return eval(expr)
except (ZeroDivisionError, TypeError):
print("Input has some bugs")
打印错误信息
def calc(expr):
try:
return eval(expr)
except (ZeroDivisionError, TypeError) as error:
print(error)
对于其他错误信息处理
def calc(expr):
try:
return eval(expr)
except ZeroDivisionError:
print("Divison by zero")
except:
print('haha, something unknown happened!')
else语句用于不出现错误信息
def calc(expr):
try:
return eval(expr)
except ZeroDivisionError:
print("Divison by zero")
else:
print("Oh, it goes well!")
此外还有finally语句,无论是否错误均会执行
实际应用:(输入表达式直到可以计算)
while True:
try:
print(eval(input()))
except:
print('Please reinput until you input the correct expression!')
else:
break;
finally:
print('I love the world whatever!') #即使else中break也会执行finally
4> 常见错误
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StandardError
| +-- BufferError
| +-- ArithmeticError
| | +-- FloatingPointError
| | +-- OverflowError
| | +-- ZeroDivisionError
| +-- AssertionError
| +-- AttributeError
| +-- EnvironmentError
| | +-- IOError
| | +-- OSError
| | +-- WindowsError (Windows)
| | +-- VMSError (VMS)
| +-- EOFError
| +-- ImportError
| +-- LookupError
| | +-- IndexError
| | +-- KeyError
| +-- MemoryError
| +-- NameError
| | +-- UnboundLocalError
| +-- ReferenceError
| +-- RuntimeError
| | +-- NotImplementedError
| +-- SyntaxError
| | +-- IndentationError
| | +-- TabError
| +-- SystemError
| +-- TypeError
| +-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- Warning
+-- DeprecationWarning
+-- PendingDeprecationWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- ImportWarning
+-- UnicodeWarning
+-- BytesWarning