python中的异常处理

xiaoxiao2021-02-28  25

异常是什么

python使用异常对象来表示异常状态,并在遇到错误时引发异常,异常对象未被处理时,程序将终止并显示一条错误信息。

让事情沿你指定的轨道出错

raise语句

In [59]: raise Exception --------------------------------------------------------------------------- Exception Traceback (most recent call last) <ipython-input-59-2aee0157c87b> in <module> ----> 1 raise Exception Exception: In [60]: raise Exception('NullPointException') --------------------------------------------------------------------------- Exception Traceback (most recent call last) <ipython-input-60-b8fd742899da> in <module> ----> 1 raise Exception('NullPointException') Exception: NullPointException

自定义异常类

class SomeCustomException(Exception): pass class MyExceptionClass(Exception): def __init__(self, code, msg): self.code = code self.msg = msg super(MyExceptionClass, self).__init__() @staticmethod def test(): content = input("input Str:") if len(content) > 5: raise MyExceptionClass('1001', '长度小于5') else: print(content) if __name__ == '__main__': MyExceptionClass.test() # input Str:123456 # Traceback (most recent call last): # File "D:/pythonProject/demo1124/com/example/demo1214/MyExceptionClass.py", line 18, in <module> # MyExceptionClass.test() # File "D:/pythonProject/demo1124/com/example/demo1214/MyExceptionClass.py", line 12, in test # raise MyExceptionClass('1001', '长度小于5') # __main__.MyExceptionClass

捕获异常

class TryDemo(object): def test(self): a = int(input("输入第一个数:")) print('\n') b = int(input("输入第二个数:")) print(a / b) if __name__ == '__main__': tryDemo = TryDemo() tryDemo.test() 输入第一个数:10 输入第二个数:0 Traceback (most recent call last): File "D:/pythonProject/demo1124/com/example/demo1214/TryDemo.py", line 12, in <module> tryDemo.test() File "D:/pythonProject/demo1124/com/example/demo1214/TryDemo.py", line 7, in test print(a / b) ZeroDivisionError: division by zero

捕获异常

def test(): a = int(input("输入第一个数:")) b = int(input("输入第二个数:")) try: print(a / b) except ZeroDivisionError: print("第二个数不能为0") class TryDemo(object): pass if __name__ == '__main__': tryDemo = TryDemo() test() 输入第一个数:10 输入第二个数:0 第二个数不能为0

不用提供参数

转载请注明原文地址: https://www.6miu.com/read-2620266.html

最新回复(0)