【Python入門自學筆記專輯】——Python異常處理

異常處理

1.1異常問題舉例

例一

>>> i = input('請輸入數字')

請輸入數字:0
>>> print(i)
0
>>> print(5 / int(i))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero

上述代碼的報錯是除零的錯誤,數學上不允許除零

例二

>>> i="QWE"
>>> print(5 / int(i))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'QWE'

i是字符串類型,而且是QWE,不能轉換成int類型,所以拋出異常

1.2異常類繼承層次

Python中的異常根類是BaseException,結構圖如下

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

1.3常見異常

1.3.1 AttributeError 異常

訪問不存在的成員

例如

>>> class Animal(object):
	pass

>>> a1 = Animal()
>>> a1.run()
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    a1.run()
AttributeError: 'Animal' object has no attribute 'run'
>>> 
>>> print(a1.age)
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    print(a1.age)
AttributeError: 'Animal' object has no attribute 'age'

程序中創建了一個類叫Animal,但是並沒有run函數和age變量,所以拋出異常

1.3.2 OSError 異常

OSError是操作系統相關異常,例如試圖打開一個不存在的文件

>>> f=open("abc.txt")
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    f=open("abc.txt")
FileNotFoundError: [Errno 2] No such file or directory: 'abc.txt'

1.3.3 IndexError 異常

是訪問元素時,下標超出索引最大值或最小值引發異常例如:

>>> code_list = [125, 56, 89, 36]
>>> code_list[4]
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    code_list[4]
IndexError: list index out of range

1.3.4 KeyError 異常

是試圖訪問字典裏不存在的鍵引發,例如:

>>> dict1[104]
Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    dict1[104]
NameError: name 'dict1' is not defined

104在字典中不存在,O(∩_∩)O哈哈~那就報錯吧

1.3.5 NameError 異常

NameError是指試圖使用一個不存在的變量引發的異常,PythonShell中運行實例

>>> value1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'value1' is not defined
>>> a = value1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'value1' is not defined
>>> value1 = 10
>>> value1
10

賦值和直接取值都不行,因爲沒有這個value1變量
只有最後的value1 = 10,才讓value1有了值

1.3.6 TypeError 異常

TypeError是試圖傳入變量類型與要求的不符合時而引發的異常。PythonShell運行實例、

>>> i = '2'
>>> print(5 / i)
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    print(5 / i)
TypeError: unsupported operand type(s) for /: 'int' and 'str'

i是一個字符類型,而5是整形,不能進行除法運算,因爲類型不統一

1.3.7 ValueError 異常

ValueError是由於傳入一個無效的參數值而引發的異常,這個異常在前面已經遇到了

>>> del i
>>> i = 'QWE'
>>> print( 5 / int(i))
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    print( 5 / int(i))
ValueError: invalid literal for int() with base 10: 'QWE'

1.4對於捕獲異常的說明

我不會捕獲異常,不會使用tryexcept等等,看也看不懂啊……😄

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章