语法错误
异常 try except else
处理异常 抛出异常 自定义异常
清理 finally/with
1 Syntax Errors
invalid syntax
2 Exceptions
Build-in Exceptions https://docs.python.org/3/library/exceptions.html#bltin-exceptions
基本架构:
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception(非系统退出的异常)
3 Handling Exceptions
- 范例
while True:
try:
x = int(input("Please enter a number: "))
break
except ValueError:
print("Oops! That was no valid number. Try again...")
先执行try里面的内容,如果没报错,except部分就跳过;如果报错了,就跳过try里面报错后面的内容;如果错误在except里面就执行except后面的语句,如果不在就传到外面的statements;如果没有找到,it is an unhandled exception and execution stops with a message as shown above.
- 多个except
可以有多个:
... except (RuntimeError, TypeError, NameError):
... pass
- 父子类except调用顺序
如果发生的异常和except
子句中的类是同一个类或者是它的基类,则异常和except子句中的类是兼容的(但反过来则不成立 --- 列出派生类的except 子句与基类兼容)。例如,下面的代码将依次打印 B, C, D
class B(Exception):
pass
class C(B):
pass
class D(C):
pass
for cls in [B, C, D]:
try:
raise cls()
except D:
print("D")
except C:
print("C")
except B:
print("B")
简单来说就是except 后面的类型,只要抛出的异常是这个类型就行(包括这个类型的子类)
- 其他
- except 子句可以省略异常名,以用作通配符。
-
try
...except
语句有一个可选的 else 子句,在使用时必须放在所有的 except 子句后面。对于在try 子句不引发异常时必须执行的代码来说很有用。例如:
https://www.zhihu.com/question/266526582
简单来说else就是没有发生异常就会执行,finally都会执行
because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try … except statement. - 异常参数
try:
raise Exception('spam', 'eggs')
except Exception as inst:
print(type(inst)) # the exception instance
print(inst.args) # arguments stored in .args
print(inst) # __str__ allows args to be printed directly,
# but may be overridden in exception subclasses
x, y = inst.args # unpack args
print('x =', x)
print('y =', y)
可以直接raise一个带参数的exception,If an exception has arguments, they are printed as the last part (‘detail’) of the message for unhandled exceptions.
instance实现了str(),所以可以直接print,或者用instance.args读,是一个tuple
4 Raising Exceptions
raise一个an exception instance or an exception class
raise ValueError # shorthand for 'raise ValueError()'
re-raise a exception
try:
raise NameError('HiThere')
except NameError:
print('An exception flew by!')
raise
5 User-defined Exceptions
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
通常自定义异常是为了后面处理的时候能取到相关的数据,当在一个模块里面抛出多种异常的时候,可以先写个基类,再写异常类继承这个基类;通常以Error开头
6 Defining Clean-up Actions
finally 子句 总会在离开 try
语句前被执行,无论是否发生了异常。 当在 try
子句中发生了异常且尚未被 except
子句处理(或者它发生在 except
或 else
子句中)时,它将在 finally
子句执行后被重新抛出。 当 try
语句的任何其他子句通过 break
, continue
或 return
语句离开时,finally
也会在“离开之前”被执行;
简单来说就是在出try语句前,必须执行finally语句
7 Predefined Clean-up Actions
with
语句允许像文件这样的对象能够以一种确保它们得到及时和正确的清理的方式使用。
with open("myfile.txt") as f:
for line in f:
print(line, end="")
网友评论