Until now, the error message has not been mentioned, but you may have seen some examples. There are at least two possible errors, syntax errors, and exceptions.
8.1 syntax error
Syntax errors, also known as parsing errors, may be the most common type of complaints you get when you are still learning Python:
The parser repeats the error line and displays a small arrow in the first place where the error is detected. The error is caused by the flag in front of the arrow. In the example, the error is detected at print (), because a colon is missing before it. The file name and row number are printed out, so you know where to enter the script to find the situation.
8.2 exceptions
Even if a statement or expression is syntactically correct, an error may occur when you try to run it. Errors detected during runtime are called exceptions and are not unconditionally fatal. later you will learn how to handle them in Python programs. Many exceptions are not processed by the program. However, the following error messages may occur:
The last line of the error message indicates what happened. An exception has different types. The types are printed as part of the message. In this example, the types are division by zero errors, name errors, and type errors. The printed string as the exception type is the name of the built-in exception. This is true for all built-in exceptions, but not necessarily true for user-defined exceptions. The standard Exception name is a built-in identifier (not a reserved keyword ).
The remaining content of this row provides detailed information based on the exception type and what causes it.
The previous part of the error message shows the context of the exception location, in the form of a stack trace. Generally, it contains a stack trace that lists the source file rows. It does not display the rows read from the standard input.
8.3 handling exceptions
You can write a program to handle the selected exceptions. As shown in the following example, the user is required to enter a valid integer until a valid integer is typed, but the user is allowed to interrupt the program. An exception is thrown when a user-generated interrupt is sent by a signal:
The try statement works as follows:
- First, the try clause (a statement between the keyword try and try t) is executed.
- If no exception occurs, the limit t clause is skipped and the try statement is executed.
- If an exception occurs during execution of the try statement, the remaining statements will be skipped. If its type matches the naming exception after limit t, the limit t clause is executed and continues to be executed after the try statement.
- If an exception occurs and it does not match the naming exception type in the clause except T, it is passed to the try Statement on the outer layer. If no handler is found, it is an unprocessed exception, the program stops running and displays the preceding error message.
A try statement may have multiple limit t clauses to specify a handler for different exceptions. At most one processing program will be executed. The handler only processes exceptions that occur in the corresponding try clause, rather than exceptions that occur in other handlers of the same try statement. A limit t clause can name multiple exceptions and use a pair of parentheses, for example:
The last occurrence t clause may ignore the Exception name as a wildcard. This should be extremely cautious, because it is easy to conceal a real programming error. It can also be used to print an error message, and then re-raise this exception (also allow the caller to handle this exception ):
The try... else t statement has an optional else clause. If so, it must be followed by all else t clauses. It is useful for code that must be executed when exceptions do not occur. For example:
The use of the else clause is better than adding additional code to the try clause, because it avoids the accidental capture of an exception and is not caused by try... caused by the Code protected by the limit t statement.
When an exception occurs, it may have an associated value, also known as an exception parameter. The appearance and type of this parameter depend on the type of the exception.
The occurrence t clause can specify a variable after the Exception name. This variable is bound to an abnormal instance and the parameters are stored in instance. args. For convenience, the exception instance defines the _ STR _ () function, so the parameters can be printed directly without referencing. args. You can instantiate an exception before triggering and add any desired attributes:
If an exception has parameters, the unhandled exceptions are printed as the last part of the information.
Exception handlers not only handle exceptions that occur directly in the try clause, but also handle exceptions in functions called (or indirectly called) in the try clause. For example:
8.4 exception
The raise statement allows programmers to force a specified exception to occur. For example:
The only parameter of raise indicates the exception. It is either an exception instance or an exception class.
If you need to determine whether an exception is thrown but do not want to handle it, a simpler raise statement allows you to trigger another exception:
8.5 user defined exception
By creating a new exception class, programs can name their own exceptions. Exceptions are typically inherited from exception classes, either directly or indirectly. For example:
In this example, the default _ init _ () of exception has been overwritten. The new behavior simply creates a value attribute. This replaces the default behavior for creating ARGs attributes.
Exception classes can be defined to do anything other classes can do, but they are usually kept simple. Generally, only some attributes are provided, allowing information about errors to be extracted by exception handlers. When creating a module that can cause several different errors, a common practice is to create a base class for all the exceptions defined in that module. For different error situations, create a specific exception subclass:
Many exceptions are defined as names ending with errors, similar to standard exceptions.
Many standard modules define their own exceptions to report errors that may occur in the functions they define.
8.6 define cleanup actions
A try statement has an optional clause that defines the cleanup action that must be executed under any circumstances. For example:
A finally clause is always executed before leaving the try statement, regardless of whether an exception occurs or not. When an exception occurs in the try clause and is not processed by a limit t clause (or an exception occurs in the limit t clause or else clause), it will be re-triggered after the finally clause is executed. When any clause of the try statement leaves through the break, continue, or return statement, the finally clause is also executed. A more complex example:
As you can see, the finally clause is executed under any circumstances. The typeerror caused by the separation of two strings is not processed by the limit t clause, so it is re-triggered after the finally clause is executed.
In real-world applications, finally clauses are very useful for releasing external resources (such as file and network connections), regardless of whether the use of resources is successful.
8.7 predefined cleanup actions
Some objects define standard cleanup actions to ensure that the object is no longer needed, no matter whether the object operation is successful or fails. Take the following example and try to open a file and print its content to the screen:
The problem with this Code is that after this part of code is executed, the open state of the file continues for an uncertain period. In a simple script, this is not a problem, but it is a problem for large applications. The with statement allows objects like files to be used in a proper and correct way to ensure they are always purged:
After the statement is executed, file F is always closed, even if a problem occurs during processing. Objects that provide predefined purge actions such as files will point this point in the document.
This article is the official website content translation, original address: http://docs.python.org/3/tutorial/errors.html