1. 程式人生 > >python 學習彙總33:異常Exception error( tcy)

python 學習彙總33:異常Exception error( tcy)

異常 


1.捕捉異常
(except訪問異常物件本身使用1個元祖1個引數)
try:
x ,y= 10,0
print (x / y )
except: #捕捉所有異常,不建議這樣使用
print( "Something wrong happened...")
except Exception: #捕捉Exception類異常
print ("Exception err!" )
except ZeroDivisionError: # 異常型別
print ("The second number can't be zero!" )
except(ZeroDivisionError,TypeError) as e: #變數 捕獲多個異常 
print ('multiple err','e=',e) # multiple err e= division by zero
else:
print('沒有錯誤發生')
finally:
print('一定會執行的語句')
pass
1.2.logging模組記錄錯誤資訊: 
# err_logging.py
import logging

def foo(s):return 10 / int(s)

def bar(s):return foo(s) *  2

def main():
try:
bar('0')
except Exception as e:
logging.exception(e)

main()
print('END')
輸出:
ZeroDivisionError: division by zero 
2. 丟擲異常                     
 (raise強制丟擲指定異常引數為異常類或異常例項):
例項1:
try:
raise Exception('err1', 'err2')
except Exception as v: #為except指定變數繫結異常例項;儲存在instance.args引數中
print('type(v)=',type(v))# the exception instance type(v)= <class 'Exception'>
print('v.args=',v.args) # arguments stored in .args ; v= v.args= ('err1', 'err2')
x, y = v.args # x= err1 y= err2

例項2:
def fun(x): #函式內部丟擲
try:
raise Exception("error!")
except Exception as err:
print(err) #error!

class c_err():
stopRaise = False
def fun1(self, expr):
try:
return eval(expr)
except (ZeroDivisionError, TypeError):
if self.stopRaise:
print ("Division by zero is illegal")
else:
raise #丟擲異常

err = c_err()
err.stopRaise = True
err.fun1("'a' / 0")
3.1. 自定義異常:
class MyError(Exception):#Exception類派生
def __init__(self, value):
self.value = value
def _out_err(self):
return "out err!"

try:
raise MyError(2*2)
except MyError as e:
print('test err! value=', e.value,e._out_err())

#結果:
#test err! value= 4 out err!  

 例項2: 

class FooError(ValueError):
pass

def foo(s):
n = int(s)
if n==0:
raise FooError('invalid value: %s' % s) #丟擲異常
return 10 / n

def bar():
try:
foo('0')
except ValueError as e:
print('ValueError!')
raise #ValueError('input error!')

bar()
#FooError: invalid value: 0 # ValueError:input error!
3.2.模組錯誤樣板: 
class Error(Exception):
"""Base class for exceptions in this module."""

class InputError(Error):
Attributes:
expression -- input expression in which the error occurred
message -- explanation of the error

def __init__(self, expression, message):
self.expression = expression
self.message = message 
4.內建異常類
Exception 所有異常基類
AttributeError 嘗試訪問未知物件屬性
IOError 開啟不存在檔案(包括其他情況)時引發
IndexError 序列中不存在索引時引發
KeyError 對映中不存在的鍵時引發
NameError 找不到名字(變數)時引發
SyntaxError 程式碼為錯誤形式時引發
TypeError 內建操作或者函式應用於錯誤型別的物件時引發
ValueError 賦值異常內建操作或函式應用於正確型別物件,物件用不合適值
ZeroDivisionError 在除法或者模除操作的第二個引數為0時引發

 異常類層次

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