异常处理
发布时间:2025-08-31 21:28:40
作者:益华网络
来源:undefined
浏览量(0)
点赞(0)
摘要:1.什么是异常 异常与错误有区别:异常可以被捕获,而错误有时候无法被捕获,语法错误会被IDE检查到,但是逻辑错误无法被知晓; 异常的产生有两种方式:使用raise语句,显式的抛出异常,还有一种是由于代码错误,解释器抛出的异常,如果没有
1.什么是异常
异常与错误有区别:异常可以被捕获,而错误有时候无法被捕获,语法错误会被IDE检查到,但是逻辑错误无法被知晓;
异常的产生有两种方式:使用raise语句,显式的抛出异常,还有一种是由于代码错误,解释器抛出的异常,如果没有进行异常捕获,就会中断程序的运行;
2.如何捕获异常try:# 这里会抛出异常,因为0不能被整除 a =1/0exceptException:print(异常)捕捉异常可以使用try/except语句;
try: 需要被捕获异常的代码块;
except :处理捕获到的异常;
3.异常的参数 一个异常可以带上参数,可作为输出的异常信息参数,可以通过except语句来捕获异常的参数; 4.异常的继承关系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+--ResourceWarning5.常用异常类介绍BaseException:所有异常类的基类都是BaseException;
Exception:所有内建,非系统退出的异常类的基类,所有自定义异常类需要继承Exception;
SystemExit:解释器请求退出;
KeyboardInterrupt:用户中断执行(通常是输入^C);
Exception:常规错误的基类;
自定义异常
classXKDException(ArithmeticError):def __init__(self,):pass6.一个完整的异常捕获try: a =1 b =0 result = a / bexceptArithmeticError:print(ArithmeticError)exceptExceptionas e:print(e)else:print(ok)finally:print(a)print(b)扫一扫,关注我们
声明:本文由【益华网络】编辑上传发布,转载此文章须经作者同意,并请附上出处【益华网络】及本页链接。如内容、图片有任何版权问题,请联系我们进行处理。
0