The error message has not been described too much so far, but the error information has been used in some examples. Python has at least two types of errors:
syntax errorAnd
Exception
8.1 Syntax Errors
Syntax errors, also known as parsing errors, are frequently complained by Python beginners.
>>> while true print (' Hello World ') File "<stdin>", line 1while True print (' Hello World ') ^ Syntaxerror:invalid syntax
The Python parser repeats the error line and displays a small arrow pointing to where the error was first detected in the error line. The error is caused by the statement in front of the arrow (at least this is detected): In the above example, the error is detected in the print()
function because the colon before it is :
missing. The file name and line number are also printed, which makes it easy to locate the problem when the program comes from the script.
8.2 Exceptions
Even if the statement or expression is syntactically correct, errors may occur at execution time. The problem detected during execution is called an exception , and the exception is not an absolute fatal error: The next step is to deal with exceptions in Python. However, most exceptions will not be processed by the program, they will eventually become error messages, shown below:
>>> (1/0) Traceback (most recent): File "<stdin>", line 1, in <module>zerodivisione Rror:division by zero>>> 4 + spam*3traceback (most recent call last): File ' <stdin> ', line 1, in <m Odule>nameerror:name ' spam ' isn't defined>>> ' 2 ' + 2Traceback (most recent call last): File "<STDIN&G t; ", line 1, in <module>typeerror:can ' t-convert ' int ' object to str implicitly
The last line of error messages indicates what happened. There are different types of exceptions, and types are printed as part of the error message: The types in the examples above have exception 0 ZeroDivisionError
, name exceptions, NameError
and type exceptions TypeError
. The string that is printed as an exception type is the name of the built-in exception. This is true for all built-in exceptions, although this Convention is useful, but not all user-defined exceptions will be followed. The standard exception name is the built-in identifier (not a reserved word).
The remaining rows show detailed information and the cause of the exception, based on the type of exception.
The previous section of the error message shows the context of the exception that occurred as a stack trace. The source code lines are usually listed in the stack backtracking, but the rows are not displayed when the program is read from standard input.
The built-in exception lists all the built-in exceptions and their meanings.
8.3 Handling Exceptions
The Python program allows handling of specified exceptions. The following program requires the user to loop input until the input is a valid integer stop, but can also interrupt the program (using Control-C
or other operating system support); Notice that user-induced interrupts throw keyboardinterrupt exceptions.
While true:try: x = int (input ("Please enter a number:")) breakexcept valueerror:print ("oops! That is no valid number. Try again ... ")
try
Statements are executed in the following order:
First, execute the try
except
try clause between and
If no exception occurs, skip the except clause and the try
statement executes
If an exception occurs during the execution of a try clause, the remaining statements within the clause are skipped. Next, if the exception type that is thrown can except
match the exception after the keyword, then the EXCEPT clause executes, and try
the statement after the statement continues execution.
If an exception occurs but does not match the exception after the except, the exception is thrown to the outer statement, and try
if the exception is not handled, the exception becomes an unhandled exception , causing the program to terminate and print the information as in the example above.
A try
statement can have multiple except clauses that specify the processing method for different exceptions. At most, only one except clause will be executed. The handler only handles exceptions that occur in the corresponding try clause, and does not handle exceptions that occur in other handlers in the same try
statement. A except clause can use a parenthesized tuple to list multiple exceptions, like this:
... except (RuntimeError, TypeError, nameerror): ... Pass
except
The class in the clause can match an exception of its subclass or its own type (but not the subclass of the EXCEPT clause that does not match the parent exception). For example, the following code prints B, C, D:
Class B (Exception):p assclass C (b):p Assclass D (c):p assfor cls in [B, C, D]:try:raise CLS () except D:print ("D") except C:prin T ("C") except B:print ("B")
Note that if the EXCEPT clause above is written except B
in reverse (before), then B, B, b--the match of the first except clause is triggered.
The last except clause can omit the exception name as a wildcard character. Because doing so will hide other real program errors, all should be used with caution. You can also use it to print error messages and re-throw them (allowing callers to handle exceptions):
Import Systry: f = open (' myfile.txt ') s = f.readline () i = Int (S.strip ()) except OSError as Err:print ("OS Erro R: {0} ". Format (ERR)) except Valueerror:print (" Could not convert data to an integer. ") Except:print ("Unexpected error:", Sys.exc_info () [0]) raise
try
...except
The statement has an optional else clause that can only appear after all except clauses. It is useful to use the ELSE clause if it is necessary to execute a piece of code if a try clause is required to not throw an exception ( else
clause is return, break, continue
skipped). For example:
For Arg in sys.argv[1:]:try: f = open (arg, ' R ') except Oserror:print (' cannot open ', arg) else:print (ARG, ' have ', Len (F.R Eadlines ()), ' lines ') f.close ()
It is else
better to use clauses than to try
attach code in clauses, because this avoids try
... except
unexpected captures that are not part of the exception that they protect from those code throws.
When an exception occurs, you can carry the value associated with it, also known as an exception parameter . Whether an exception parameter can exist and its type depends on the exception type.
The EXCEPT clause can specify a variable after the exception name. The variable is bound to an exception instance, and the exception parameter is stored in the instance.args
property. For convenience, the exception instance is defined so that the __str__()
exception parameter can be printed directly instead of using a .args
reference. You can also instantiate the exception first and add any desired arguments before throwing it:
>>> Try: ... Raise Exception (' spam ', ' eggs ') ... except Exception as inst: ... Print (Type (inst)) # The exception instance ... Print (Inst.args) # arguments stored in. Args ... Print (inst) # __str__ allows args to be printed directly,... # but May is overridden in exception subclasses ... X, y = Inst.args # unpack args ... Print (' x = ', x) ... Print (' y = ', y) ... <class ' Exception ' > (' spam ', ' eggs ') (' spam ', ' eggs ') x = Spamy = Eggs
For unhandled exceptions, if it has parameters, the parameters are printed in the later part of the error message (Details section).
Exception handlers not only handle exceptions that occur immediately in a try clause, but also handle exceptions that occur in functions that are called directly or indirectly in a try clause. For example:
>>> def this_fails (): ... x = 1/0...>>> Try: ... This_fails () ... except zerodivisionerror as err: ... Print (' Handling run-time error: ', err) ... Handling Run-time Error:division by zero
8.4 Raising Exceptions
The Raise statement allows the programmer to force an exception to occur. For example:
>>> Raise Nameerror (' Hithere ') Traceback (most recent call last): File "<stdin>", line 1, in <module >nameerror:hithere
raise
The unique parameter specifies the exception to throw. The parameter must be an exception instance or an exception class (inheriting from the subclass of the exception class). If the argument is an exception type, an exception instance is implicitly initialized with a constructor that calls the exception without a parameter:
Raise ValueError # shorthand for ' raise valueerror () '
If you need to catch an exception but not handle it, a simpler form of raise
statement allows the exception to be re-thrown:
>>> Try: ... Raise Nameerror (' Hithere ') ... except nameerror: ... Print (' An exception flew by! ') ... Raise ... An exception flew by! Traceback (most recent): File "<stdin>", line 2, in <module>nameerror:hithere
8.5 user-defined Exception
You can make your own exceptions by creating new exception classes (see Classes
Getting more information on Python classes). Exceptions must be inherited directly or indirectly from the Exception
class.
Custom exception classes have the functionality of other classes, but they usually need to be concise and provide only a few properties for the exception handler to extract the error information. When you need to create a module that throws several different errors, it is a good practice to create a parent class for defining exceptions in this module, and subclasses to create specific exceptions that correspond to different errors:
Class Error (Exception): "" "Base class for exceptions in the This module." " Passclass Inputerror (Error): "" "Exception raised for errors in the input. Attributes: expression--input expression in which the error occurred message--Explanation of the error "" " def __init__ (self, expression, message): Self.expression = Expressionself.message = MessageClass transitionerror (Error) : "" "raised when an operation attempts a state transition that's not allowed. Attributes: previous-state at beginning of transition next – attempted new state message--Explanation of Why the specific transition isn't allowed "" " def __init__ (self, previous, Next, message): Self.previous = Previoussel F.next = nextself.message = Message
Similar to the standard exception class, the names of most exceptions end with "Error".
Many standard modules define their own exceptions, which correspond to errors that may occur in the functions defined in the module. For more information, refer to classes.
8.6 Defining clean-up Actions
try
Statements have optional clauses that execute in any case, and can be used to define cleanup actions. For example:
>>> Try: ... Raise Keyboardinterrupt ... finally: ... Print (' Goodbye, world! ') ... Goodbye, world! Keyboardinterrupttraceback (most recent): File "<stdin>", line 2, in <module>
Thefinally clause is always executed before leaving the statement, regardless of whether an exception occurred try
. When try
an exception occurs in the clause and is not handled by the except
clause (or if the exception occurs in except
clauses or clauses else
), the finally
clauses are re-thrown after they are executed. try
clauses are also executed when other clauses of the statement pass break, continue
or the return
statement leaves finally
. The following are more complex examples:
>>> def divide (x, y): ... Try: ... result = X/y ... Except Zerodivisionerror: ... Print ("Division by Zero!") ... else: ... Print ("result is", result) ... Finally: ... Print ("executing finally clause") ...>>> divide (2, 1) result is 2.0executing finally clause>>> divide (2 , 0) Division by zero!executing finally clause>>> divide ("2", "1") executing finally Clausetraceback (most recent C All last): file ' <stdin> ', line 1, in <module> file ' <stdin> ', line 3, in Dividetypeerror:unsup Ported operand type (s) for/: ' STR ' and ' str '
As you can see, finally
clauses are executed under any circumstances. The exception generated by dividing two strings is TypeError
not except
handled by the clause, so it finally
is re-thrown after the clause has finished executing.
In a practical application, finally
clauses are used to release external resources, such as files and network connections, regardless of the success of the resource's use.
8.7 Predefined clean-up Actions
Some objects define standard cleanup actions that, when these objects are no longer needed, perform cleanup actions regardless of whether the operation using the object succeeds. The following example reads the file and prints the contents to the display:
For On open ("MyFile.txt"):p rint (line, end= "")
The problem with this code is that when the code finishes executing, the file remains open for an indeterminate period of time. This is not a big problem in a simple script, but it can be problematic in large applications. with
statements allow objects like files to be immediately and accurately recycled.
With open ("MyFile.txt") as F:for line in F:print (line, end= "")
After the statement executes, the file F is always closed, even if you encounter problems executing the code. objects that provide predefined cleanup actions, like files, indicate this in their documentation.