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
<完>
异常处理与自定义异常详解
本文详细介绍了Python中try...except语句的使用方法,包括如何捕获特定类型的异常,自定义异常类,以及异常类的继承关系。通过实例演示了如何在不同情况下执行不同的代码块,并解释了Exception类的args属性及其在打印异常信息时的作用。
1054

被折叠的 条评论
为什么被折叠?



