熱線電話:13121318867

登錄
首頁精彩閱讀Python函數的周期性執行實現方法
Python函數的周期性執行實現方法
2018-02-11
收藏

Python函數的周期性執行實現方法

通過創建一個新的異常類,程序可以命名它們自己的異常。異常應該是典型的繼承自Exception類,通過直接或間接的方式。
以下為與RuntimeError相關的實例,實例中創建了一個類,基類為RuntimeError,用于在異常觸發時輸出更多的信息。

在try語句塊中,用戶自定義的異常后執行except塊語句,變量 e 是用于創建Networkerror類的實例。    
class Networkerror(RuntimeError):
  def __init__(self, arg):
   self.args = arg

在你定義以上類后,你可以觸發該異常,如下所示:
    
try:
  raise Networkerror("Bad hostname")
except Networkerror,e:
  print e.args

在下面這個例子中,默認的__init__()異常已被我們重寫。   
>>> class MyError(Exception):
...   def __init__(self, value):
...     self.value = value
...   def __str__(self):
...     return repr(self.value)
...
>>> try:
...   raise MyError(2*2)
... except MyError as e:
...   print 'My exception occurred, value:', e.value
...
My exception occurred, value: 4
>>> raise MyError, 'oops!'
Traceback (most recent call last):
 File "<stdin>", line 1, in ?
__main__.MyError: 'oops!'

常見的做法是創建一個由該模塊定義的異?;惡妥宇?,創建特定的異常類不同的錯誤條件。

我們通常定義的異常類,會讓它比較簡單,允許提取異常處理程序的錯誤信息,當創建一個異常模塊的時候,常見的做法是創建一個由該模塊定義的異?;惡妥宇?,根據不同的錯誤條件,創建特定的異常類:    
class Error(Exception):
  """Base class for exceptions in this module."""
  pass
 
class InputError(Error):
  """Exception raised for errors in the input.
 
  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
 
class TransitionError(Error):
  """Raised when an operation attempts a state transition that's not
  allowed.
 
  Attributes:
    previous -- state at beginning of transition
    next -- attempted new state
    message -- explanation of why the specific transition is not allowed
  """
 
  def __init__(self, previous, next, message):
    self.previous = previous
    self.next = next
    self.message = message

數據分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數據分析師資訊
更多

OK
客服在線
立即咨詢
日韩人妻系列无码专区视频,先锋高清无码,无码免费视欧非,国精产品一区一区三区无码
客服在線
立即咨詢