Python built-in exception Architecture
The class hierarchy for built-in exceptions is:
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StandardError
| +-- BufferError
| +-- ArithmeticError
| | +-- FloatingPointError
| | +-- OverflowError
| | +-- ZeroDivisionError
| +-- AssertionError
| +-- AttributeError
| +-- EnvironmentError
| | +-- IOError
| | +-- OSError
| | +-- WindowsError (Windows)
| | +-- VMSError (VMS)
| +-- EOFError
| +-- ImportError
| +-- LookupError
| | +-- IndexError
| | +-- KeyError
| +-- MemoryError
| +-- NameError
| | +-- UnboundLocalError
| +-- ReferenceError
| +-- RuntimeError
| | +-- NotImplementedError
| +-- SyntaxError
| | +-- IndentationError
| | +-- TabError
| +-- SystemError
| +-- TypeError
| +-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- Warning
+-- DeprecationWarning
+-- PendingDeprecationWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- ImportWarning
+-- UnicodeWarning
+-- BytesWarning
Capture exceptions
Method 1: capture all exceptions
''' The first way to capture exceptions, capture all exceptions ''' try: a = B = c except t Exception, data: print Exception ,":", data ''' output: <type 'exceptions. exception '>: local variable' B' Referenced before assignment'' |
Method 2: Use the traceback module to view exceptions. Import the traceback module.
'''Second way to capture exceptions, use traceback to view exceptions ''' Try: A = B B = c Except t: Print traceback. print_exc () '''Output: Traceback (most recent call last ): File "test. py", line 20, in main A = B UnboundLocalError: local variable 'B' referenced before assignmen |
Method 3: Use the sys module to trace the final exception
'''Third way to capture exceptions, use the sys module to capture exceptions ''' Try: A = B B = c Except t: Info = sys. exc_info () Print info Print info [0] Print info [1] ''' Output: (<Type 'exceptions. unboundlocalerror'>, UnboundLocalError ("local Variable 'B' referenced before assignment ",), <Traceback object at 0x00D243F0>) <Type 'exceptions. unboundlocalerror'> Local variable 'B' referenced before assignment ''' |