2014-11-05 97 views
7

我想以某種方式處理特定異常,並一般地記錄所有其他異常。 這是我有:Python處理多個異常

class MyCustomException(Exception): pass 


try: 
    something() 
except MyCustomException: 
    something_custom() 
except Exception as e: 
    #all others 
    logging.error("{}".format(e)) 

的問題是,即使MyCustomException將被記錄,因爲它從Exception繼承。我能做些什麼來避免這種情況?

+0

你是如何提高'的東西()'裏面?如果它引發了一個'MyCustomException',這段代碼可以正常工作。 – 2014-11-05 14:41:38

回答

6

你的代碼還在發生什麼?

MyCustomException應檢查和前流過到達所述第二except子句

In [1]: def test(): 
    ...:  try: 
    ...:   raise ValueError() 
    ...:  except ValueError: 
    ...:   print('valueerror') 
    ...:  except Exception: 
    ...:   print('exception') 
    ...:   

In [2]: test() 
valueerror 

In [3]: issubclass(ValueError,Exception) 
Out[3]: True 
6

只有除塊中的第一匹配將被執行的處理:

class X(Exception): pass 

try: 
    raise X 
except X: 
    print 1 
except Exception: 
    print 2 

只打印1

即使您在除外塊中引發異常,它也不會被其他塊捕獲:

class X(Exception): pass 

try: 
    raise X 
except X: 
    print 1 
    0/0 
except Exception: 
    print 2 

打印1,提高ZeroDivisionError: integer division or modulo by zero