Python learning-Exception Handling, python-Exception Handling
The Exceptions in Python are the base classes of all exceptions. The built-in exception classes are placed in the Exceptions module. You can see these built-in classes through the dir () function.
Use raise statements to trigger exceptions, as shown in figure
>>> Raise Exception
>>>import exceptions
>>>dir(exceptions)['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'EnvironmentError', 'Exception', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__doc__', '__name__', '__package__']
When the code encounters an error, it will spread up layer by layer. If no exception capture mechanism is found, the error will be transmitted to the location of the global variable, causing the program to end with an error.
In python, try/try t can be used to catch exceptions. try t can catch up with built-in exception classes or custom exception classes.
1 import exceptions2 try: 3 print a4 partition t NameError: 5 print 'undefined name'View Code can also capture multiple exceptions and use tuples to list them. In addition, if you want to access the exception object itself, add a parameter to the compile t statement, such as import exceptionstry: print aworkflow t NameError, e: print eView Code
Note: In python 3.0, the alias t statement is written as execpt NameError as e:
Other statements:
Else statement: else runs only when no exception is found.
Finally statement: all statements in exception handling are executed.