转自Manually raising (throwing) an exception in Python
def demo_bad_catch(): # Avoid raising a generic Exception
try:
raise ValueError('Represents a hidden bug, do not catch this')
raise Exception('This is the exception you expect to handle')
except Exception as error:
print('Caught this error: ' + repr(error))
>demo_bad_catch()
>Caught this error: ValueError('Represents a hidden bug, do not catch this',)
def demo_no_catch(): # more specific catches won't catch the general exception:
try:
raise Exception('general exceptions not caught by specific handling')
except ValueError as e:
print('we will not catch exception: Exception')
>demo_no_catch()
>Exception Traceback (most recent call last)
<ipython-input-4-ec39b7ba8683> in <module>()
----> 1 demo_no_catch()
<ipython-input-3-c6f2d59e41ed> in demo_no_catch()
1 def demo_no_catch():
2 try:
----> 3 raise Exception('general exceptions not caught by specific handling')
4 except ValueError as e:
5 print('we will not catch exception: Exception')
Exception: general exceptions not caught by specific handling
try:
raise ValueError('A very specific bad thing happened', 'foo', 'bar', 'baz')
except ValueError as err:
print(err.args)
> ('A very specific bad thing happened', 'foo', 'bar', 'baz')
try:
raise ValueError('A very specific bad thing happened', 'foo', 'bar', 'baz')
except ValueError as err:
raise
> ValueError Traceback (most recent call last)
<ipython-input-6-d323cf99e315> in <module>()
1 try:
----> 2 raise ValueError('A very specific bad thing happened', 'foo', 'bar', 'baz')
3 except ValueError as err:
4 raise
ValueError: ('A very specific bad thing happened', 'foo', 'bar', 'baz')
- Exception hierarchy
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StopAsyncIteration
+-- ArithmeticError
| +-- FloatingPointError
| +-- OverflowError
| +-- ZeroDivisionError
+-- AssertionError
+-- AttributeError
+-- BufferError
+-- EOFError
+-- ImportError
| +-- ModuleNotFoundError
+-- LookupError
| +-- IndexError
| +-- KeyError
+-- MemoryError
+-- NameError
| +-- UnboundLocalError
+-- OSError
| +-- BlockingIOError
| +-- ChildProcessError
| +-- ConnectionError
| | +-- BrokenPipeError
| | +-- ConnectionAbortedError
| | +-- ConnectionRefusedError
| | +-- ConnectionResetError
| +-- FileExistsError
| +-- FileNotFoundError
| +-- InterruptedError
| +-- IsADirectoryError
| +-- NotADirectoryError
| +-- PermissionError
| +-- ProcessLookupError
| +-- TimeoutError
+-- ReferenceError
+-- RuntimeError
| +-- NotImplementedError
| +-- RecursionError
+-- SyntaxError
| +-- IndentationError
| +-- TabError
+-- SystemError
+-- TypeError
+-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- Warning
+-- DeprecationWarning
+-- PendingDeprecationWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- ImportWarning
+-- UnicodeWarning
+-- BytesWarning
+-- ResourceWarning