Python has two types of errors that are easily recognizable: syntax errors and exceptions.
Syntax error
The syntax error of Python, or it is called parsing fault, is often encountered by beginners, the following example
>>> while True print (' Hello world ') File "<stdin>", line 1, in? While True print (' Hello world ') ^syntaxerror:invalid syntax
In this example, the function print () is checked for errors, and a colon (:) is missing in front of it.
The parser points to the wrong line and marks a small arrow at the location of the first found error.
Abnormal
Even if the syntax of the Python program is correct, an error may occur when you run it. The run-time detected error is called an exception.
Most exceptions are not handled by the program, and are presented here in the form of an error message:
>>> (1/0) Traceback (most recent): File "<stdin>", line 1, in? Zerodivisionerror:division by zero>>> 4 + spam*3traceback (most recent call last): File "<stdin>", Lin E 1, in? Nameerror:name ' spam ' isn't defined>>> ' 2 ' + 2Traceback (most recent call last): File "<stdin>", line 1, in? Typeerror:can ' t convert ' int ' object to str implicitly
Exceptions occur in different types, which are printed as part of the information: the types in the examples are zerodivisionerror,nameerror and TypeError.
The previous section of the error message shows the context in which the exception occurred and displays the specific information as the call stack.
Exception handling
In the following example, let the user enter a valid integer, but allow the user to interrupt the program (using Control-c or the method provided by the operating system). User-interrupted information throws a Keyboardinterrupt exception.
>>> while True: try: x = int (input ("Please enter a number:")) break except ValueError: Print ("Oops! That is no valid number. Try again ")
The Try statement works in the following manner;
- First, execute the TRY clause (the statement between the keyword try and the keyword except)
- If no exception occurs, the EXCEPT clause is ignored, and the try clause finishes after execution.
- If an exception occurs during the execution of a try clause, the remainder of the try clause is ignored. If the type of the exception matches the name after except, then the corresponding except clause is executed. The code after the last try statement is executed.
- If an exception does not match any of the except, then the exception is passed to the upper try.
A try statement may contain multiple except clauses that handle different specific exceptions. Only one branch will be executed at most.
The handler will handle only the exceptions in the corresponding try clause, not the exceptions in the other try handlers.
A except clause can handle multiple exceptions at the same time, and the exceptions are placed in parentheses into a tuple, for example:
Except (RuntimeError, TypeError, Nameerror): Pass
The last except clause can ignore the name of the exception and it will be used as a wildcard character. You can use this method to print an error message and then throw the exception again.
Import Systry: f = open (' myfile.txt ') s = f.readline () i = Int (S.strip ()) except OSError as err: print (" OS error: {0} ". Format (ERR)) except ValueError: print (" Could not convert data to an integer. ") Except: print ("Unexpected error:", Sys.exc_info () [0]) raise
The try except statement also has an optional ELSE clause, which, if used, must be placed after all the except clauses. This clause will be executed when no exception occurs in the TRY clause. For example:
For ARG in sys.argv[1:]: try: f = open (arg, ' R ') except IOError: print (' Cannot open ', arg) else: Print (ARG, ' has ', Len (F.readlines ()), ' lines ') f.close ()
It is better to use the ELSE clause than to put all the statements in a try clause, which avoids unexpected, except, and uncaught exceptions.
Exception handling not only handles exceptions that occur directly in a try clause, but also handles exceptions thrown in functions called in clauses (even indirectly called functions). 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:int division or modulo by zero
Throw exception
Python throws a specified exception using the Raise statement. For example:
>>> Raise Nameerror (' Hithere ') Traceback (most recent call last): File "<stdin>", line 1, in? Nameerror:hithere
Raise only one parameter specifies the exception to be thrown. It must be an instance of an exception or an exception class (that is, a subclass of Exception).
If you just want to know if this throws an exception and don't want to deal with it, then a simple raise statement can throw it again.
>>> try: raise Nameerror (' Hithere ') except Nameerror: print (' An exception flew by! ') Raise an exception flew by! Traceback (most recent): File ' <stdin> ', line 2, in? Nameerror:hithere
User-defined exceptions
You can have your own exception by creating a new Exception class. Exceptions should inherit from the Exception class, either directly or indirectly, for example:
>>> class Myerror (Exception): def __init__ (self, value): self.value = value def __str__ (self): return repr (self.value) >>> try: raise Myerror (2*2) except Myerror as E: print (' My Exception occurred, value: ', E.value) My exception occurred, value:4>>> raise Myerror (' oops! ') Traceback (most recent): File "<stdin>", line 1, in? __main__. Myerror: ' oops! '
In this example, the class Exception default __init__ () is overwritten.
Classes that <p exceptions can do anything like other classes, but they are usually simpler, provide only some attributes that are error-related, and allow code that handles exceptions to easily get that information.
When creating a module that is likely to throw many different exceptions, it is common practice to create a base exception class for the package, and then, based on the underlying class, to make different subclasses for different error conditions:
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 = expression self.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 are not allowed "" " def __init__ (self, previous, Next, message): Self.previo US = previous Self.next = next self.message = message
Most of the names of the exceptions end with "Error" and are named after the standard exception.
Define cleanup behavior
The try statement has another optional clause that defines the cleanup behavior that will be performed regardless of the circumstances. For example:
>>> try: raise Keyboardinterrupt finally: print (' Goodbye, world! ') Goodbye, world! Keyboardinterrupt
In the above example, the FINALLY clause executes if no exception occurs in the TRY clause.
If an exception is thrown in a try clause (or in the except and ELSE clause) without any except intercepting it, the exception is thrown again after the finally clause is executed.
The following is a more complex example (including the except and finally clauses in the same try statement):
>>> 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>&G T;> Divide ("2", "1") executing finally Clausetraceback (most recent call last): File ' <stdin> ', line 1, in?
file "<stdin>", line 3, in dividetypeerror:unsupported operand type (s) for/: ' STR ' and ' str '
Pre-defined cleanup behavior
Some objects define the standard cleanup behavior, regardless of whether the system successfully uses it, and once it is not needed, the standard cleanup behavior is performed.
This example shows an attempt to open a file and then print the content to the screen:
For On open ("MyFile.txt"): print (line, end= "")
The problem with the above code is that when execution is complete, the file remains open and is not closed.
The keyword with statement will ensure that objects such as files are used to perform their cleanup correctly after they are exhausted:
With open ("MyFile.txt") as F: for line in F: print (line, end= "")
When the above code is executed, the file F is always closed, even if there is a problem during processing.
Python3 Errors and exceptions