34, python exception handling throws and customization

Insert picture description here

print("Test Exception")

list1 = []
try:
    print(list1[3])
except IndexError:
    print("IndexError")
    
try:
    print(list1[3])
except IndexError as e: # 把错误内容给打印出来
    print("IndexError:", e)

Program output:

Test Exception
IndexError
IndexError: list index out of range

  • If we don’t know the type of exception

# 如果我们不知道异常的类型
list1 = []
try:
    print(list1[3])
except :
    print("未知异常")
    
try:
    print(list1[3])
except Exception as e: # 所有异常都继承自Exception这样一个类,所以我们统一捕获这个异常
    print("未知异常:", e)

Program output:

未知异常
未知异常: list index out of range
  • There can be multiple except statements
# except语句可以有多条
list1 = []
try:
    print(list1[3])
except NameError:
    print("名字错误")
except IndexError:
    print("名字错误")
except :
    print("未知异常")

Program output:

名字错误

  • The else statement and finally statement after the except statement

# except语句后面的else语句和finally语句
list1 = []
try:
    print(list1[3])
except Exception as e:
    print("未知异常:", e)
else:
    print("没有抛出异常")
finally:
    print("任何情况都进入1")
    
try:
    pass
except:
    pass
else:
    print("没有抛出异常")
finally:
    print("任何情况都进入2")

Program output:

未知异常: list index out of range
任何情况都进入1
没有抛出异常
任何情况都进入2



Custom exception

Insert picture description here
The way to throw an exception is to throw an exception directly, which means to throw an object.
For custom exceptions, we can customize a class by ourselves. As long as we inherit Exception, your class can be thrown as an exception; of course, you can also directly inherit classes with index errors and name errors, and there is no problem.

# 自定义异常
class XError(Exception):
    def __init__(self, value = ""): # 在抛出一个异常的时候,可以传一个值进来
        self.value = value
    
    # 用来print异常信息
    def __str__(self):
        return "XError :" + str(self.value)

# 抛出我们自定义的异常
try:
    raise XError("test error") # 抛出异常
except XError as e:
    print(e)

Program output:

XError :test error

Let's reload a function like __str__. The purpose of overloading this function is mainly to make our exception be printed directly. The purpose of __str__ is to print our exception directly, because there are many exceptions to deal with. This error is displayed to it.

Guess you like

Origin blog.csdn.net/zhaopeng01zp/article/details/109317878
Recommended