Python common exceptions and handling

1. What is an exception

Exception : The code is completely correct, but the error exception/error will be reported during the running of the program.
Features : When the program encounters an exception during execution, the program will terminate at the code where the exception occurred, and the code will not continue to next execution

2. Common exceptions

exception name explain
NameError variable is not defined
TypeError type error
IndexError index exception
keyError Exception raised by using a key that does not exist in the dictionary
ValueError Exception raised when a method receives an argument of the correct data type but with an inappropriate value
AttributeError attribute exception
ImportError Path exception when importing module
SyntaxError code doesn't compile
UnboundLocalError Attempt to access a local variable that has not been set

Example: An array out of bounds triggers an exception error

3. Exception handling method

Solution: Override the exception and ensure that the following code continues to execute [Essence: Temporarily shield the exception, the purpose is to keep the execution of the following code from being affected]

(1) Catch exceptions

  1. try-except-else

grammar:

​ try:
​ codes that may have exceptions
except error code as variable:
statement 1
except error code as variable:
statement 2
······
​ else:
statement n

illustrate:

① The usage of try-except-else is similar to that of if-elif-else
​ ② Else is optional, depending on the specific needs
​ ③ The code block after the try is called the monitoring area [detect whether the code in it is abnormal
] ④ Working principle: first execute the statement in try, if there is no exception in the statement in try, skip all the except statements directly and execute else; if the statement in try is abnormal, go to the except branch to match the error code, if If the match is found, execute the statement after except; if there is no match for except, the exception is still not intercepted [shielded]

Example:

#一、try-except-else的使用

#1.except带有异常类型
try:
    print(10 / 0)
except ZeroDivisionError as e:
    print("被除数不能为0",e)

print("~~~~")
"""
总结:
a.try-except屏蔽了异常,保证后面的代码可以正常执行
b.except ZeroDivisionError as e相当于声明了一个ZeroDivisionError类型的变量【对象】,变量e中携带了错误的信息
"""

#2.try后面的except语句可以有多个
class Person(object):
    __slots__ = ("name")
try:
    p = Person()
    p.age = 19

    print(10 / 0)
except AttributeError as e:
    print("属性异常",e)
except ZeroDivisionError as e:
    print("被除数不能为0",e)

print("over")

"""
总结:
a.一个try语句后面可以有多个except分支
b.不管try中的代码有多少个异常,except语句都只会被执行其中的一个,哪个异常处于try语句的前面,则先先执行对应的except语句
c.后面的异常不会报错【未被执行到】
"""

#3.except语句的后面可以不跟异常类型
try:
    print(10 / 0)
except:
    print("被除数不能为0")


#4.一个except语句的后面可以跟多种异常的类型
#注意:不同的异常类型使用元组表示
try:
    print(10 / 0)
except (ZeroDivisionError,AttributeError):
    print("出现了异常")


#5.else分支
try:
    print(10 / 4)
except ZeroDivisionError as e:
    print("出现了异常",e)
else:
    print("hello")

"""
总结:
a.如果try中的代码出现了 异常,则直接去匹配except,else分支不会被执行
b.如果try中的代码没有出现异常,则try中的代码正常执行,except不会被执行,else分支才会被执行
"""

#6.try中不仅可以直接处理异常,还可以处理一个函数中的异常
def show():
    x = 1 / 0

try:
    show()
except:
    print("出现了异常")

#7.直接使用BaseException代替所有的异常
try:
    y = 10 / 0
except BaseException as e:
    print(e)

"""
总结:在Python中,所有的异常其实都是类,他们都有一个共同的父类BaseException,可以使用BaseException将所有异常“一网打尽”
"""

  1. try-except-finally

grammar:

try:
​ codes that may have exceptions
except error code as variable:
statement 1
except error code as variable:
statement 2
······
​ finally:
statement n

Description: Regardless of whether there is an exception in the statement in the try, no matter whether the exception matches the except statement, the finally statement will be executed

Role: Indicates the definition of cleanup behavior, indicating the operations that need to be performed under any circumstances

Example:

#二、try-except-finally的使用

#1.
try:
    print(10 / 5)
except ZeroDivisionError as e:
    print(e)

finally:
    print("finally被执行")


#2.特殊情况
#注意:当在try或者except中出现return语句时,finally语句仍然会被执行
def show():
    try:
        print(10 / 0)
        return
    except ZeroDivisionError as e:
        print(e)

    finally:
        print("finally被执行~~~~")

show()

(2) Throw an exception

  1. raise
    raise raises a specified exception object
    Syntax: raise exception object or raise
    description: exception object is created by error code, generally speaking, the more accurate the error code is, the better

Example:

	e = Exception("Time ERROR")
	raise e
#raise的使用主要体现在自定义异常中

#1.raise表示直接抛出一个异常对象【异常是肯定存在的】
#创建对象的时候,参数表示对异常信息的描述
try:
    raise NameError("hjafhfja")
except NameError as e:
    print(e)

print("over")

"""
总结:
通过raise抛出的异常,最终还是需要通过try-except处理
"""

#2.如果通过raise抛出的异常在try中不想被处理,则可以通过raise直接向上抛出
try:
    raise NameError("hjafhfja")
except NameError as e:
    print(e)
    raise

  1. assert assertion
    Make a prediction about a problem, if the prediction is successful, get the result; if the prediction fails, print the prediction information
    Syntax: assert expression, information description when an exception occurs
def func(num,divNum):
    #assert关键字的作用:预测表达式是否成立,如果成立,则执行后面的代码;如果不成立,则将异常的描述信息打印出来
    assert (divNum != 0),"被除数不能为0"

    return  num / divNum

print(func(10,20))
print(func(10,0))

Guess you like

Origin blog.csdn.net/qq_43619058/article/details/125088768