Exception

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


<完>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值