Python3 常见的内置异常

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

语法错误SyntaxError

Python
In [3]: print "hell" File "<ipython-input-3-eac92f10c9db>", line 1 print "hell" ^ SyntaxError: Missing parentheses in call to 'print'
1
2
3
4
5
In [ 3 ] : print "hell"
   File "<ipython-input-3-eac92f10c9db>" , line 1
     print "hell"
               ^
SyntaxError : Missing parentheses in call to 'print'

异常exceptions

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

Python
>>> 10 * (1/0) Traceback (most recent call last): File "<stdin>", line 1, in ? ZeroDivisionError: int division or modulo by zero >>> 4 + spam*3 Traceback (most recent call last): File "<stdin>", line 1, in ? NameError: name 'spam' is not defined >>> '2' + 2 Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: Can't convert 'int' object to str implicitly
1
2
3
4
5
6
7
8
9
10
11
12
>>> 10 * ( 1 / 0 )
Traceback ( most recent call last ) :
   File "<stdin>" , line 1 , in ?
ZeroDivisionError : int division or modulo by zero
>>> 4 + spam * 3
Traceback ( most recent call last ) :
   File "<stdin>" , line 1 , in ?
NameError : name 'spam' is not defined
>>> '2' + 2
Traceback ( most recent call last ) :
   File "<stdin>" , line 1 , in ?
TypeError : Can 't convert ' int' object to str implicitly

捕获所有异常

Python
while True: try: x = int(input("Please enter a number: ")) break except Exception as e: print('start e'.center(50, '*')) print(e) print('end e'.center(50, '*')) print("Oops! That was no valid number. Try again ")
1
2
3
4
5
6
7
8
9
while True :
     try :
         x = int ( input ( "Please enter a number: " ) )
         break
     except Exception as e :
         print ( 'start e' . center ( 50 , '*' ) )
         print ( e )
         print ( 'end e' . center ( 50 , '*' ) )
         print ( "Oops!  That was no valid number.  Try again   " )

输出结果是:

➜ 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

Python
In [2]: a = [1,2,3] In [3]: a[3] --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-3-94e7916e7615> in <module>() ----> 1 a[3] IndexError: list index out of range
1
2
3
4
5
6
7
8
9
In [ 2 ] : a = [ 1 , 2 , 3 ]
 
In [ 3 ] : a [ 3 ]
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
IndexError                                  Traceback ( most recent call last )
< ipython - input - 3 - 94e7916e7615 > in < module > ( )
-- -- > 1 a [ 3 ]
 
IndexError : list index out of range

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



  • zeropython 微信公众号 5868037 QQ号 5868037@qq.com QQ邮箱
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值