怎么解決Python中自定義異常-創(chuàng)新互聯(lián)

創(chuàng)新互聯(lián)www.cdcxhl.cn八線動態(tài)BGP香港云服務(wù)器提供商,新人活動買多久送多久,劃算不套路!

成都創(chuàng)新互聯(lián)10多年成都企業(yè)網(wǎng)站定制服務(wù);為您提供網(wǎng)站建設(shè),網(wǎng)站制作,網(wǎng)頁設(shè)計(jì)及高端網(wǎng)站定制服務(wù),成都企業(yè)網(wǎng)站定制及推廣,對隧道混凝土攪拌車等多個方面擁有豐富的網(wǎng)站推廣經(jīng)驗(yàn)的網(wǎng)站建設(shè)公司。

這篇文章將為大家詳細(xì)講解有關(guān)怎么解決Python中自定義異常,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。

通過創(chuàng)建一個新的異常類,程序可以命名它們自己的異常。異常應(yīng)該是典型的繼承自Exception類,通過直接或間接的方式。

以下為與RuntimeError相關(guān)的實(shí)例,實(shí)例中創(chuàng)建了一個類,基類為RuntimeError,用于在異常觸發(fā)時輸出更多的信息。

在try語句塊中,用戶自定義的異常后執(zhí)行except塊語句,變量 e 是用于創(chuàng)建Networkerror類的實(shí)例。

class Networkerror(RuntimeError):
  def __init__(self, arg):
   self.args = arg

在你定義以上類后,你可以觸發(fā)該異常,如下所示:

try:
  raise Networkerror("Bad hostname")
except Networkerror,e:
  print e.args

在下面這個例子中,默認(rèn)的__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!'

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

我們通常定義的異常類,會讓它比較簡單,允許提取異常處理程序的錯誤信息,當(dāng)創(chuàng)建一個異常模塊的時候,常見的做法是創(chuàng)建一個由該模塊定義的異?;惡妥宇?,根據(jù)不同的錯誤條件,創(chuàng)建特定的異常類:

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

關(guān)于怎么解決Python中自定義異常就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

網(wǎng)站名稱:怎么解決Python中自定義異常-創(chuàng)新互聯(lián)
標(biāo)題鏈接:http://www.muchs.cn/article8/epoip.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供關(guān)鍵詞優(yōu)化、企業(yè)建站、電子商務(wù)、ChatGPT、服務(wù)器托管、標(biāo)簽優(yōu)化

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

商城網(wǎng)站建設(shè)