Python3 常见的内置异常-新乡seo|网站优化,网站建设_微信公众号:zeropython—昊天博客

你在编写Python代码时可能已经遇到过一些。Python 中(至少)有两种错误:语法错误和异常( syntax errorsexceptions )。

语法错误SyntaxError

异常exceptions

即使一条语句或表达式在语法上是正确的,当试图执行它时也可能会引发错误。运行期检测到的错误称为 异常,并且程序不会无条件的崩溃:很快,你将学到如何在 Python 程序中处理它们。然而,大多数异常都不会被程序处理,像这里展示的一样最终会产生一个错误信息:

捕获所有异常

输出结果是:

➜ d9 python3 c1.py
Please enter a number: 99l
*********************start e**********************
invalid literal for int() with base 10: '99l'
**********************end e***********************
Oops! That was no valid number. Try again
Please enter a number: 99

异常基类有那些呢?

BaseException

所有异常的根类,所有内置异常都是派生该类

Exception

所有与程序有关的异常基类,这些异常包括除了SystemExit, GenratorExit 和 KeyboardInterrupt之外的其他异常

LookupErro

索引和键错误的基类, 包括IndexErro 和 KeyErro

EnvironmentError

在PYTHON外部发生的错误积累, 包括了IOError OSError

异常内置关系图:
[code]
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