概述
异常
1.捕捉异常
(except访问异常对象本身使用1个元祖1个参数)
try:
x ,y= 10,0
print (x / y )
except: #捕捉所有异常,不建议这样使用
print( "Something wrong happened...")
except Exception: #捕捉Exception类异常
print ("Exception err!" )
except ZeroDivisionError: # 异常类型
print ("The second number can't be zero!" )
except(ZeroDivisionError,TypeError) as e: #变量 捕获多个异常
print ('multiple err','e=',e) # multiple err e= division by zero
else:
print('没有错误发生')
finally:
print('一定会执行的语句')
pass
1.2.logging模块记录错误信息:
# err_logging.py
import logging
def foo(s):return 10 / int(s)
def bar(s):return foo(s) * 2
def main():
try:
bar('0')
except Exception as e:
logging.exception(e)
main()
print('END')
输出:
ZeroDivisionError: division by zero
2. 抛出异常
(raise强制抛出指定异常参数为异常类或异常实例):
实例1:
try:
raise Exception('err1', 'err2')
except Exception as v: #为except指定变量绑定异常实例;存储在instance.args参数中
print('type(v)=',type(v))# the exception instance type(v)= <class 'Exception'>
print('v.args=',v.args) # arguments stored in .args ; v= v.args= ('err1', 'err2')
x, y = v.args # x= err1 y= err2
实例2:
def fun(x): #函数内部抛出
try:
raise Exception("error!")
except Exception as err:
print(err) #error!
class c_err():
stopRaise = False
def fun1(self, expr):
try:
return eval(expr)
except (ZeroDivisionError, TypeError):
if self.stopRaise:
print ("Division by zero is illegal")
else:
raise #抛出异常
err = c_err()
err.stopRaise = True
err.fun1("'a' / 0")
3.1. 自定义异常:
class MyError(Exception):#Exception类派生
def __init__(self, value):
self.value = value
def _out_err(self):
return "out err!"
try:
raise MyError(2*2)
except MyError as e:
print('test err! value=', e.value,e._out_err())
#结果:
#test err! value= 4 out err!
实例2:
class FooError(ValueError):
pass
def foo(s):
n = int(s)
if n==0:
raise FooError('invalid value: %s' % s) #抛出异常
return 10 / n
def bar():
try:
foo('0')
except ValueError as e:
print('ValueError!')
raise #ValueError('input error!')
bar()
#FooError: invalid value: 0 # ValueError:input error!
3.2.模块错误样板:
class Error(Exception):
"""Base class for exceptions in this module."""
class InputError(Error):
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
4.内建异常类
Exception 所有异常基类
AttributeError 尝试访问未知对象属性
IOError 打开不存在文件(包括其他情况)时引发
IndexError 序列中不存在索引时引发
KeyError 映射中不存在的键时引发
NameError 找不到名字(变量)时引发
SyntaxError 代码为错误形式时引发
TypeError 内建操作或者函数应用于错误类型的对象时引发
ValueError 赋值异常内建操作或函数应用于正确类型对象,对象用不合适值
ZeroDivisionError 在除法或者模除操作的第二个参数为0时引发
异常类层次
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StopAsyncIteration
+-- ArithmeticError
| +-- FloatingPointError
| +-- OverflowError
| +-- ZeroDivisionError
+-- AssertionError
+-- AttributeError
+-- BufferError
+-- EOFError
+-- ImportError
| +-- ModuleNotFoundError
+-- 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
| +-- RecursionError
+-- SyntaxError
| +-- IndentationError
| +-- TabError
+-- SystemError
+-- TypeError
+-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- Warning
+-- DeprecationWarning
+-- PendingDeprecationWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- ImportWarning
+-- UnicodeWarning
+-- BytesWarning
+-- ResourceWarning
最后
以上就是冷傲小伙为你收集整理的python 学习汇总33:异常Exception error( tcy)的全部内容,希望文章能够帮你解决python 学习汇总33:异常Exception error( tcy)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复