[Python notes]: exception handling Error

Posted by matt2012 on Fri, 04 Mar 2022 03:54:49 +0100

abnormal

1. Definition:

Errors detected at runtime.

2. Phenomenon:

When an exception occurs, the program will not execute down, but go to the call statement of the function.

3. Common exception types:

– name error: the variable is undefined.
– type error: operation with different types of data.
– index error: out of index range.
– attributeerror: the object does not have an attribute with the corresponding name.
– key error: there is no key with the corresponding name.
– not implemented error: a method that has not been implemented.
– Exception base class Exception.

handle

try/except
Exception capture can use the try/except statement.

while True:
    try:
        x = int(input("Please enter a number: "))
        break
    except ValueError:
        print("The number you entered is not a number, please try again!")

The try statement works as follows:;

  • First, execute the try clause (the statement between the keyword try and the keyword except).
  • If no exception occurs, the exception clause is ignored and the try clause ends after execution.
  • If an exception occurs during the execution of the try clause, the rest of the try clause is ignored. If the exception type and exception
    If the subsequent names match, the corresponding except clause will be executed.
  • If an exception does not match any except, the exception will be passed to the upper try.

A try statement may contain multiple except clauses to handle different specific exceptions. At most one branch will be executed.
The handler will only handle exceptions in the corresponding try clause, not exceptions in other try handlers.
An exception clause can handle multiple exceptions at the same time. These exceptions will be placed in a bracket to become a tuple

1. Syntax:

try:
Statements that may trigger exceptions
Exception error type 1 [as variable 1]:
Processing statement 1
Exception error type 2 [as variable 2]:
Processing statement 2
except Exception [as variable 3]:
Not a processing statement of the above error type
else:
Statement without exception
finally:
Whether or not an exception occurs
For example:

def div_apple(apple_count):
    # Divide apples
    person_count = int(input("Please enter the number of people:"))  # ValueError
    result = apple_count / person_count  # ZeroDivisionError
    print("Everyone divided%d An apple" % result)

try:
    div_apple(10)
except ValueError as e:  # Catch exception of ValueError type
    print("The number of people entered is incorrect")
except ZeroDivisionError:  # Catch exception of type ZeroDivisionError
    print("Number cannot be zero")
except Exception as e:  # Catch all types of exceptions
    print("Error of unknown type")
else:  # No exception occurred and the logic was executed
    print("Apple distribution succeeded")
finally:
    print("Whether or not an exception occurs,All execute logic")
print("Subsequent logic.......")

2. Function:

Change the program from abnormal state to normal process.

3. Description:

The as clause is a variable used to bind the wrong object and can be omitted
The except clause can have one or more to catch some type of error.
There can be at most one else clause.
There can be at most one finally clause. If there is no except clause, it must exist.
If the exception is not caught, it will continue to be passed to the upper layer (call place) until the program terminates.
try/except...else
The try/except statement also has an optional else clause. If this clause is used, it must be placed after all except clauses.

print("Give me two number,and I'll divide them.")
print("Enter 'q' to quit")

while True:
    frist_number = input("\n First number: ")
    if frist_number == "q":
        break
    second_number = input("Second number: ")
    try:
        answer = int(frist_number) / int(second_number)
    except ZeroDivisionError:
        print("You can't divide by 0")
    else:
        print(answer)

Print results

Give me two number,and I'll divide them.
Enter 'q' to quit

 First number: 12
Second number: 0
You can't divide by 0

 First number: 12
Second number: 3
4.0

 First number: q

Try finally statement
The try finally statement executes the last code regardless of whether an exception occurs.

Throw exception

Python uses the raise statement to throw a specified exception.
The syntax format of raise is as follows: raise [Exception [, args [, traceback]]]

raise statement
    1. Function: throw an error and let the program enter the abnormal state.
    2. Purpose: when the number of layers of program calls is deep, it is troublesome to pass error information to the calling function layer by layer. Therefore, if you throw an exception artificially, you can directly pass the error information.

x = 10
if x > 5:
    raise Exception('x Cannot be greater than 5. x The value of is: {}'.format(x))

Topics: Python