Python program development -- Chapter 9 exception handling

Keywords: Python

1, Abnormal

Exceptions in python are implemented through classes. All exception classes inherit from the base class BaseException, which can be divided into four categories as follows:

If the exception in the program is not handled, the exception will be passed to the upper level by default, which is the delivery of the exception. If the upper level has not been handled, it will continue to be delivered upward until the exception is handled or the program crashes.

2, Catch exception

(1) try... except statement

This statement is used to catch the exception when the program is running. The try clause is followed by the code, and the exception clause is followed by the caught exception type and the handling code when the exception is caught. In short, if there is an exception in the try clause, the remaining code in the clause will be ignored and the code in the exception clause will be executed immediately. If there is no exception in the try clause, the content after the exception clause will not be executed.

try:
	code
except(Exception type):
	Exception handling code

Standard exceptions in python are as follows: python standard exception
For example, in the following python code, NameError is generated because the d variable is not declared in the try clause: the exception of undeclared / initialized object (no attribute), and the exception is detected in the except clause, so the correct code is executed:

try:
    a = 1
    b = 2
    c = a * d
    print(c)
except NameError:
    c = a * b
    print(c)
    

The operation results are as follows:

1. Single exception

It can be used to record specific exception types in the form of as e/error followed by exception types, where e/error obtains exception information.
For example, the following python code:

try:
    a = 1
    b = 2
    c = a * d
    print(c)
except NameError as e:
    print(f"The program is abnormal due to:{e}")
    c = a * b
    print(c)

The operation results are as follows. The name'd 'is not defined is the recorded exception information:

2. Multiple exceptions

There may be multiple exceptions in the code. You can put the exception class after the exception clause or use multiple exception clauses.
For example, in the following python code, except (TypeError, NameError) as error means to output exception information when there is an operation (TypeError) or undeclared / initialized object (NameError) with invalid type in the program:

try:
    def function(a, b):
        print(a, b)
    function(2, 3, 4)
except (TypeError, NameError) as error:
    print(f"The program is abnormal due to:{error}")
    

The operation results are as follows:

You can also write multiple except clauses separately, that is, which clause to execute when there are different exceptions in the program.
For example, the following python code receives a standard input data c and outputs the data through the input() function when there is an operation invalid for the type in the program, and outputs the recorded exception information when there is an exception of undeclared / initialized object in the program:

try:
    def function(a, b):
        a = b + c
        print(a)
    function(1, 2)
except TypeError as error:
    print(f"The program is abnormal due to:{error}")
except NameError as error:
    print(f"The program is abnormal due to:{error}")
    c = input("Please enter a variable c Value of:")
    print(c)

The operation results are as follows, because the variable c is not declared:

3. Omit exception class

Omitting the exception class is the exception type after omitting the exception clause, indicating that all caught program exceptions are handled.
For example, the following python code:

try:
    a = 1
    b = 2
    c = a + d
    print(c)
except:
    print("Exception caught!")

The operation results are as follows:

(2) try... except... else statement

Add an else clause after the try... except statement. The content of this clause is the code executed when no exception occurs in the try clause.
For example, the following python code outputs a prompt when the program has an exception of undeclared / initialized objects. If there is no exception, it outputs the value of a-b:

try:
    a = 1
    b = 2
    c = a + b
    print(c)
except NameError:
    print("Undeclared/Initialize object!")
else:
    c = a - b
    print(c)

The operation results are as follows:

(3) try... except... finally statement

When the try... except statement is used together with the finally clause, it means that the code in the finally clause will be executed whether an exception is caught or not. For example, the finally clause is used when processing a file, that is, to close the file, so as to avoid occupying resources.
For example, in the following python code, no matter whether there is an exception in the finally clause, the file.close() in the clause must be closed:

try:
    file = open("file1.txt", mode="r", encoding="utf-8")
    file.write("123456789")
except Exception as error:
    print(f"File writing failed! as a result of:{error}")
finally:
    file.close()
    print("The file has been closed!")

The operation results are as follows:

You can also release the file through the with statement. After the statement is executed, the with statement will close the file. If the file cannot be opened, the file will also be closed. The format is as follows:

with Context expression [as Resource object]
	sentence

The context expression here returns a context Explorer object. If the as clause is specified, the context of the context Explorer object will be returned__ enter__ The return value of () method is assigned to the resource object. In addition, it should be noted that not all objects can use the with statement, and only objects that support the context management protocol can use the statement.

3, Throw exception

Catching exceptions can be understood as that the program has an exception and the system reports an error. In addition, we can actively throw exceptions through relevant statements.

(1) raise statement

1. Exception type throws an exception

The raise statement is followed by the exception type, that is, you can throw an exception by using the name of the exception type.
For example, the following python code throws an overflow error exception by using the raise statement, which indicates that the numerical operation exceeds the maximum limit:

raise OverflowError

The operation results are as follows:

2. The exception object throws an exception

For example, the following python code creates an obj of the overflow error class_ Error object and throw the object through raise statement:

obj_error = OverflowError()
raise obj_error

The operation results are as follows:

3. Exception thrown by exception

By using the raise keyword alone, you can re throw the exception that occurred.
For example, the following python code:

try:
    print(a)
except NameError as error:
    print(f"File writing failed! as a result of:{error}")
    raise
    

The operation results are as follows:

(2) assert assertion statement

The assert assertion statement is used to judge whether an expression is true. If it is false, an assertion error exception will be thrown. The format is as follows. The expression is the object of judgment, and the parameter is usually a user-defined string describing the specific information of the exception:

assert expression[,parameter]

For example, in the following python code, the 1 < - 1 expression is false, so the program throws an AssertionError exception:

a = 1
b = -1
assert a < b

The operation results are as follows:

4, Custom exception

Although many Exception types are defined in python, we can also customize exceptions by creating a class to inherit Exception class or other classes.
For example, in the following python code, first customize the exception my_ The error class calls the Exception of the base class in its class construction method. init__ Method and takes exception information as a parameter

class my_error(Exception):
    def __init__(self, error="Format error"):
        super().__init__(error)


def f_main():
    file_name = input("Please enter file name:")
    try:
        if file_name.split(".")[1] in ["txt", "doc"]:
            print("File name is normal!")
        else:
            raise my_error()
    except Exception as error:
        print(f"The program is abnormal due to:{error}")


f_main()

The operation results are as follows:

Posted by jackohara on Sat, 20 Nov 2021 12:13:00 -0800