try..exception的写法如下所示,当文件不存在的时候出现error,输入错误信息
当文件存在时,执行else语句,关闭文件。不管OK还是NG都会执行finally语句。
import sys
try:
f = open("mfile.txt")
except IOError as e:
print("NO mfile.txt")
print("system error message is :{0}".format(e))
else:
print("close mfile")
f.close()
finally:
print("finally")
Exception有个特殊tuple属性args用来存储参数,同样默认的__str__也是用的参数,所以在有参数并且没有定义__str__的Exception中,直接打印对象和args是相同的。
try:
raise Exception('spam', 'eggs')
except Exception as e:
print(type(e))
print(e.args)
print(e)
#输出结果为
<class 'Exception'>
('spam', 'eggs')
('spam', 'eggs')
自定义Exception
class MyError(Exception):
def __init__(self, myarg):
self.myarg = myarg
def __str__(self):
return self.myarg
if __name__ == "__main__":
try:
raise MyError("my error")
except MyError as e:
print(e.args)
print(e)
# 输出结果
# ('my error',)
# my error
Python的内置异常类的继承关系如下所示
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- ArithmeticError
| +-- FloatingPointError
| +-- OverflowError
| +-- ZeroDivisionError
+-- AssertionError
+-- AttributeError
+-- BufferError
+-- EOFError
+-- ImportError
+-- LookupError
| +-- IndexError
| +-- KeyError
+-- MemoryError
+-- NameError
| +-- UnboundLocalError
+-- OSError
| +-- BlockingIOError
| +-- ChildProcessError
| +-- ConnectionError
| | +-- BrokenPipeError
| | +-- ConnectionAbortedError
| | +-- ConnectionRefusedError
| | +-- ConnectionResetError
| +-- FileExistsError
| +-- FileNotFoundError
| +-- InterruptedError
| +-- IsADirectoryError
| +-- NotADirectoryError
| +-- PermissionError
| +-- ProcessLookupError
| +-- TimeoutError
+-- ReferenceError
+-- RuntimeError
| +-- NotImplementedError
+-- SyntaxError
| +-- IndentationError
| +-- TabError
+-- SystemError
+-- TypeError
+-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- Warning
+-- DeprecationWarning
+-- PendingDeprecationWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- ImportWarning
+-- UnicodeWarning
+-- BytesWarning
+-- ResourceWarning
<完>