Subdirectory
8.1 Syntax Error 8.2 Exceptions 8.3 Processing Exceptions 8.4 Throwing Exceptions 8.5 User Custom Abnormal 8.6 Defining Cleaning Behavior
8. Error and exception
So far, there is no further talk about error messages, but in those examples you have tried, it may have been encountered. There are two errors in Python (at least): Syntax Errors and Exceptions.
8.1 Syntax error
Syntax errors, also known as parsing errors, may be the easiest to learn Python:
>>> While True Print 'Hello World'
File "
", LINE 1, IN?"
While True Print 'Hello World'
^
SyntaxError: Invalid Syntax
The parser repeats the wrong line and displays a small arrow at the wrong position in the previous row. Error (at least detected) occurs at the point where the arrow is pointing. The error in the example is on the keyword print, because there is a colon (:) before it. At the same time, the file name and the line number will be displayed so you can know which script from the error comes from.
8.2 exception
Even when you have a fully correct statement, it is possible to do it when you try to execute it. The error detected in the program is called an exception, which usually does not lead to fatal problems, and you will soon learn how to control them in the Python program. Most exceptions will not be handled by the program, but to display an error message:
>>> 10 * (1/0)
TRACEBACK (MOST RECENT CALL LAST):
File "
", LINE 1, IN?"
ZerodivisionError: Integer Division or MODULO by Zero
>>> 4 SPAM * 3
TRACEBACK (MOST RECENT CALL LAST):
File "
", LINE 1, IN?"
Namerror: Name 'spam' is not defined
>>> '2' 2
TRACEBACK (MOST RECENT CALL LAST):
File "
", LINE 1, IN?"
TypeError: Cannot Concatenate 'Str' and 'Int' Objects
The last line of the error message indicates something wrong. Exceptions also have different types, and the exception type is displayed as part of the error message: the exceptions in the example are zero-era errors, named errors, and type errors. When printing an error message, the anomalous type is displayed as an exception's internal name. This is the case for all built-in abnormalities, but the user's custom exception is not necessarily (although this is a very useful agreement). The standard exception name is a built-in identifier (no keywords).
This line is a detailed description of this exception type, which means its content is dependent on an exception type.
The first half of the error message lists an abnormal position in the form of a stack. Source code rows are usually listed in the stack, however, the source code from the standard input will not be displayed.
The Python Library Reference Manual lists the built-in exceptions and their meaning.
8.3 processing exception
The specified exception can be processed by programming. The following example repeats the user to enter a value until the user enters a legal integer. However, this program allows the user to interrupt the program (using a method of supporting the Control-C or other operating system). It should be noted that the interrupt of the user will trigger a keyboardInterrupt exception. >>> While True:
... TRY:
... x = int (Raw_Input ("" please enter a number: "))
... BREAK
... Except ValueError:
... Print "OOPS! That Was No Valid Number. Try Again ..."
...
The TRY statement works as follows:
First, execute the TRY clause (part between TRY and Except keywords). If there is no abnormality, the Except clause is ignored after the TRY sentence is executed. If an exception occurs during the execution of the Try clause, the rest of the subsept will be ignored. If the exception matches the exception type specified after the Except keyword, the corresponding ExcePT clause is performed, and other parts of the TRY clause is ignored. Then continue the code after the TRY statement. If an exception has occurred, there is no branch that matches it in the Except clause, it will pass to the previous TRY statement. If the corresponding processing statement is still not found, it becomes an unprocessed exception, the termination program is run, and the prompt information is displayed.
A TRY statement may contain multiple Except clauses, specifying different exceptions, respectively. At most, there will be only one branch is executed. The exception handler will only process an exception that occurred in the corresponding TRY clause, in the same TRY statement, the abnormality that occurs in other clauses is not processed. An Except clause can list multiple exception names in parentheses, for example:
... ExcePt (RuntimeError, TypeError, NameError):
... Pass
The last Except clause can omit an abnormal name and use it as a communication. Be careful to use this method, because it is likely to block the real program error, can't find it! It can also be used to print a row error message and then re-throw an exception (which can make the caller better process exception).
Import string, sys
TRY:
f = open ('myfile.txt')
s = f.readline ()
i = int (String.Strip (s))
Except Ioerror, (Errno, STRERROR):
Print "I / O Error (% S):% S"% (errno, strrror)
Except ValueError:
Print "Could Not Convert Data to An Integer."
Except:
Print "Unexpected Error:", sys.exc_info () [0]
Raise
The TRY ... Except statement can have an else clause that can only appear after all Except clauses. When the TRY is not thrown out, you need to perform some code, you can use this clause. E.g:
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 ()
Using the Else clause is better than adding a code in the TRY clause, because this avoids the exception thrown by Try ... Except unexpected interception that does not belong to those code they protected.
When an exception occurs, there may be an accessory value as an abnormal parameter. Whether this parameter exists, what type is dependent on an exception type.
After the exception name (list), a variable can also be specified for the Except clause. This variable is bound to an exception instance, which is stored in the parameter of Instance.Args. For convenience, the abnormal instance defines __getitem__ and __str__, so you can directly access the print parameters without having to reference .args.
>>> TRY:
... Raise Exception ('spam', 'eggs')
... Except Exception, INST:
... Print Type (INST) # The Exception Instance
... Print Inst.Args # arguments stored in .args
... Print Inst # __STR__ALLOWS ARGS to Printed Directly
... x, y = INST # __GETITEM__ALLOWS ARGS TO BE Unpacked Directly
... Print 'x =', X
... Print 'Y =', Y
...
('spam', 'eggs')
('spam', 'eggs')
X = spam
Y = Eggs
For unprocessed exceptions, if it has a parameter, it will be printed as the last part of the error message ("details").
Exception handle can do not allow the exception that occurs directly in the TRY clause, even in which the function is (or even indirect), an exception occurs, or can be processed. E.g:
>>> DEF this_fails ():
... x = 1/0
...
>>> TRY:
... this_fails ()
... Except ZerodiVisionerror, Detail:
... Print 'Handling Run-Time Error:', Detail
...
Handling Run-Time Error: Integer Division or MODULO
8.4 Throwing anomalies
When a specific exception has occurred, the programmer can force the abnormality with the RAISE statement. E.g:
>>> Raise NameError, 'Hithere'
TRACEBACK (MOST RECENT CALL LAST):
File "
", LINE 1, IN?"
Namerror: Hithere
The first parameter specifies the name of the abnormality thrown, the second specified parameters.
If you decide to throw an exception without dealing with it, the Raise statement allows you to quickly reap out the exception.
>>> TRY:
... Raise NameError, 'Hithere'
... except nameerror: ... print 'an exception flevY!'
... raise
...
An Exception Flew By!
TRACEBACK (MOST RECENT CALL LAST):
File "
", LINE 2, IN?"
Namerror: Hithere
8.5 User Customization
You can name your own exception by creating a new exception type. Abnormal classes should usually be derived from the Exception class 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, E:
... Print 'My Exception Occurred, Value:', E.Value
...
MY Exception Occurred, Value: 4
>>> Raise MyError, 'OOPS!'
TRACEBACK (MOST RECENT CALL LAST):
File "
", LINE 1, IN?"
__main __. myerror: 'OOPS!'
Anything in any other class can be defined in any other class, but usually in order to maintain a simple, only several attribute information are added to an exception handle extract. If you need to throw several different errors in a newly created module, a usual process is to define an exception base class for the module and then give a corresponding exception subclass for different error type.
Class Error (Exception):
"" "Base Class for Exceptions in this module." ""
PASS
Class InputError (Error):
"" "Exception raised for errors in the input.
Attributes:
Expression - INPUT Expression in which the error occurre
Message - Explanation of the error
"" "
DEF __INIT __ (Self, Expression, Message):
Self.Expression = Expression
SELF.MESSAGE = Message
Class TransitionError (ERROR):
"" "Raised when an operation attempts a state transition That's Not
ALOWED.
Attributes:
Previous - State At Beginning Of Transition
Next - Attempted New State
Message - Explanation of why the specific Transition is not allowed
"" "
Def __init __ (self, previous, next, message):
Self.previous = previous
Self.next = Nextself.Message = Message
Similar to standard abnormalities, most abnormal namings end with "error".
Many standard modules have defined their own exceptions to report errors that may occur in the functions they define. For further information on the class, see Chapter 9, "Class".
8.6 Defining Cleaning Behavior
The TRY statement has another optional clause that defines the functions that must be performed in any case. E.g:
>>> TRY:
... Raise KeyboardInterrupt
... Finally:
... Print 'Goodbye, World!'
...
Goodbye, World!
TRACEBACK (MOST RECENT CALL LAST):
File "
", LINE 2, IN?"
KeyBoardInterrupt
The Finally clause will be executed regardless of the exception in the TRY clause. If an exception occurs, it will be reappeared after the finally clause is executed. The TRY clause will also perform a Finally clause via Break or Return.
The code in the Finally clause is used to release external resources (such as files or network connections), regardless of whether these resources have been successfully utilized.
Several Except clauses or a finally clause can be used in the TRY statement, but both cannot coexist.