First, what is abnormal
An exception is the error signal generation program is running (when the program error occurs, an exception, if the program does not handle it, it will throw the exception, run the program also will be terminated)
Common exception:
AttributeError no attempt to access an object tree, such as foo.x, but foo does not attribute the X- IOError input / output abnormalities; basically can not open the file ImportError not import module or package; basically a question or path name is wrong IndentationError syntax error (subclass); the code is not properly aligned IndexError subscript index out of sequence boundaries, such as when only three elements of x, is trying to access x [. 5] a KeyError attempts to access the dictionary does not exist in the bond KeyboardInterrupt Ctrl + C is pressed NameError use a variable has not been given an object SyntaxError Python code is illegal, the code does not compile (personally think it's a syntax error, wrong) TypeError incoming object type does not comply with the requirements of UnboundLocalError attempt to access a local variable has not been set , basically due to a global variable otherwise the same name leads you to think that it is being accessed ValueError incoming caller does not expect a value, even if the value of the type is correct
Second, exception handling
1. If an error condition is predictable, we need to deal with if: prevention before the error occurred
= 10 of AGE the while True: age = INPUT ( '>>:') .strip () IF age.isdigit (): # Only when a string is an integer of age, the following code will not an error, the condition is predict Age = int (Age) IF == Age of AGE: Print ( 'you GOT IT') BREAK
2. If the error condition is unpredictable, you need to use try ... except: processing after an error
# Basic syntax of try: code block to be detected except exception types: the try in the event of an anomaly is detected, the logic of the implementation of this position # Example try: F = Open ( 'a.txt') G = (line.strip () Line F in for) Print (Next (G)) Print (Next (G)) Print (Next (G)) Print (Next (G)) Print (Next (G)) the except the StopIteration: f.close ()
Third, an exception is thrown
Use the raise statement throws a specific exception in Python, we can use the class or instance parameter called the raise statement throws an exception. Examples are as follows:
class EvaException(BaseException): def __init__(self,msg): self.msg=msg def __str__(self): return self.msg try: raise EvaException('类型错误') except EvaException as e: print(e)
Fourth, the catch multiple exceptions
We said earlier, how to deal with an unusual situation, if it comes to more, how can we deal with that?
Support a try / except statement handle multiple exceptions in Python, the syntax is as follows:
try: <statement> the except <exception name>: Print ( 'Exceptions Description') the except <exception name>: Print ( 'Exceptions Description') works try statement is as follows: first the try statement in the block, if no exception occurs, except in words is ignored, after the end of the try statement block of code. If the try statement block abnormal, try the rest of the statements are ignored, if abnormal and eccept name has been abnormal, except the corresponding statement is executed. If an exception does not match, the exception is passed to the top of the try statement, a statement may contain first except statement, they were treated for different exceptions, but most only one branch will be executed. the try: #a is #. 1/0 DIC = {. 1: 2} DIC [. 3] the except NameError: Print ( 'name is not defined, given a') the except the ZeroDivisionError: Print ( '0 is not used as the divisor, the error') the except a KeyError : Print ( 'without the key')
Five kinds of abnormal else
After executing the program if we also want to do other things abnormality how to do? Then we can use the exception else, the specific syntax is as follows:
try: <statements> the except <abnormalities name>: <statement> the except <abnormalities name>: <statement> the else: <statement> # (try statement did not execute this code after an exception) if executed in the try statement no exception occurs will be executed else statement, else statement than to use all the statements are placed inside try words better, to avoid some unexpected but except there caught exception: DEF FUNC (the X-, the y-): try: a X = / Y the except: Print ( 'Error, Happened') the else: Print ( 'It execpt Wentworth AS') FUNC (2,1)
Six user-defined exception
MyError with the class (Exception): DEF the __init __ (Self, value): self.value value = DEF __str __ (Self): return the repr (self.value) the try: The raise MyError with the (2 * 2) the except MyError with the AS E: Print ( 'My occurred Exception, value: ', e.Value) My Exception occurred, value: 4 The raise MyError (' oops')! Traceback (MOST recent Results Last Call): ? File "<stdin>", Line 1, in . main __ MyError: 'oops!' in this example, the default class Exception __init __ () is covered. When you create a module may throw a number of different abnormalities A common practice is to create a base exception class for this package, and then create different sub-classes for different error conditions on the base class: class Error (Exception ): "" "Base class for Exceptions and in the this Module." "" Pass class InputError (Error): "" " Attributes: expression -- input expression in which the error occurred 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 allowed. 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 = next self.message = message Most unusual name has the "Error" at the end, just like a standard naming as abnormal.
Seven, the definition of clean-up behavior (finally)
The try statement has another optional clause, which defines the clean-up will be carried out regardless of the behavior under any circumstances. E.g:
The try >>>: ... The raise KeyboardInterrupt ... a finally: ... Print ( 'Goodbye, world!') ... Goodbye, world! Traceback (MOST recent Results Last Call): File "<stdin>", Line 2, in <Module1> the KeyboardInterrupt above examples regardless try clause there are no exception occurs, finally clause are executed. If an exception in the try clause (or except and else clause) is thrown out, but do not have any except it stopped, then this will be raised again after the finally clause is executed. Here is a more complex example (contained in the same statement in a try except and finally clauses): >>> DEF Divide (the X-, the y-): try: the Result = the X-/ the y- except ZeroDivisionError: Print ( "Division by ZERO! ") the else: Print (" the Result IS ", the Result) a finally: Print (" Executing a finally clause " IS 2.0 Result the finally clause Executing >>> Divide (2, 0) Division by ZERO! Executing the finally clause >>> Divide ( "2", ". 1") Executing the finally clause Traceback (MOST Recent Last Call): File "<stdin>", Line 1, in? File "<stdin>", Line 3, in Divide TypeError: Unsupported operand of the type (S) for /: 'str' and 'str' predefined clean-up behavior of some objects define standard clean-up behavior, regardless whether the system successfully used it once does not need it anymore, then the standard clean-up behavior will be executed. This example shows this side try to open a file, then print the content on the screen: for in Open Line ( "myfile.txt"): Print (Line, End = "") issue more than this code, when executed after completion, the file remains open, and not closed. Keywords with statement can be guaranteed, such as object files and the like will carry out his right cleaning method after use: print (line, end = "" ) or more after the implementation of the code, even if in the process a problem, file f is always closed.
# 1 exception class can only be used to handle specific exceptions, if you can not deal with non-specified exception. S1 = 'Hello' the try: int (S1) the except IndexError AS E: # uncaught exception, the program directly given Print E # 2 multibranched S1 = 'Hello' the try: int (S1) the except IndexError AS E: Print (E ) the except a KeyError AS E: Print (E) the except a ValueError AS E: Print (E) #. 3 universal exception exception S1 = 'Hello' the try: int (S1) the except exception AS E: Print (E) #. 4 multibranched abnormal universal abnormal # 4.1 if you want the effect, no matter what is abnormal, we unified discarded, or use the same code logic to deal with them, then show in bold to do it, there is only one Exception enough. # 4.2 if you want to effect that, for different exception we need to customize different processing logic, it would need to use a multi-branch. # 5 can also be a multi-branch later Exception S1 = 'Hello' the try: int (S1) the except IndexError AS E: Print (E) the except a KeyError AS E: Print (E) the except a ValueError AS E: Print (E) the except Exception AS E: Print (E) #. 6 abnormal other means S1 = 'Hello' the try: int (S1) the except IndexError AS E: Print (E) the except a KeyError AS E: Print (E) the except a ValueError AS E: Print (E) #except Exception AS E: # Print ( E) the else: Print ( 'within the try block is executed without exception I') the finally: Print ( 'whether abnormal or not, the module will be executed, is generally carried out cleanup') # 7 active trigger abnormal try: raise TypeError ( 'type error') the except Exception AS E: Print (E) #. 8 custom exception class EgonException (BaseException): DEF the __init __ (Self, MSG): self.msg = MSG DEF __str __ (Self): return Self. MSG the try: the raise EgonException ( 'error type') the except EgonException AS E: Print (E) # asserted. 9: assert condition assert. 1. 1 == assert. 1 == 2 # 10 summarizes the try..except . 1: the true error handling and work separate 2: code easier to organize, clearer and complex tasks easier to implement; 3: without a doubt, more secure, and will not due to the negligence of some small unexpected collapse of the program;
python standard exceptions
The exception name | description |
---|---|
BaseException | Base class for all exceptions |
SystemExit | Interpreter exit request |
KeyboardInterrupt | User Interrupt Executing (usually enter ^ C) |
Exception | General Error base class |
StopIteration |
Iterator no more value |
GeneratorExit | To notify the exit exception generator (generator) occurs |
StandardError | All standard exceptions built base class |
ArithmeticError | All numerical errors base class |
FloatingPointError | Floating-point calculation error |
OverflowError | Exceeds the maximum limit value calculation |
ZeroDivisionError | In addition to (or modulus) of zero (all data types) |
AssertionError | Assertion failure |
AttributeError | Object does not have this property |
EOFError | No built-in input, to reach the EOF marker |
EnvironmentError | OS Error base class |
IOError | Input / output operations to fail |
OSError | Operating system error |
WindowsError | System call fails |
ImportError | Import module / object failed |
LookupError | Invalid class data base query |
IndexError | Without this sequence index (index) |
KeyError | Without this key mapping |
MemoryError | Memory overflow error (for Python interpreter is not fatal) |
NameError | Undeclared / initialize objects (no attributes) |
UnboundLocalError | Local access uninitialized variables |
ReferenceError | Weak reference object (Weak reference) have been trying to access a garbage collection of |
RuntimeError | General runtime error |
NotImplementedError | The method has not been implemented |
SyntaxError | Python syntax error |
IndentationError | Indentation errors |
TabError | Tab and space mix |
SystemError | General interpreter system error |
TypeError | Invalid type of operation |
ValueError | Invalid parameter passed |
UnicodeError | Unicode related errors |
UnicodeDecodeError | Error when decoding of Unicode |
UnicodeEncodeError | Unicode encoding error |
UnicodeTranslateError | Unicode conversion error |
Warning | Warning base class |
DeprecationWarning | Warning about deprecated features |
FutureWarning | Warning about the future structure of the semantics have changed |
overflow Warning | The old warning about automatically promoted to a long integer (long) of |
PendingDeprecationWarning | Will be warned about the characteristics of the waste |
RuntimeWarning | 可疑的运行时行为(runtime behavior)的警告 |
SyntaxWarning | 可疑的语法的警告 |
UserWarning | 用户代码生成的警告 |