2017-08-17 40 views
1

我使用的是其中在一個點一個異常被定義爲一個Python庫:如何捕捉自定義異常在Python

raise Exception("Key empty") 

我現在希望能夠趕上那特定的異常,但我我不知道該怎麼做。

我嘗試以下

try: 
    raise Exception('Key empty') 
except Exception('Key empty'): 
    print 'caught the specific exception' 
except Exception: 
    print 'caught the general exception' 

但只是打印出caught the general exception

有沒有人知道我怎麼可以捕捉到特定的Key empty異常?歡迎所有提示!

回答

2

定義你的例外:

class KeyEmptyException(Exception): 
    def __init__(self, message='Key Empty'): 
     # Call the base class constructor with the parameters it needs 
     super(KeyEmptyException, self).__init__(message) 

使用它:

try: 
    raise KeyEmptyException() 
except KeyEmptyException as e: 
    print e 

更新:基於在評論OP的討論貼:

但LIB是不是我的控制之下。它是開源的,所以我可以編輯它,但我最好試着在不編輯庫的情況下捕捉它。這不可能嗎?

說庫會引發異常的

# this try is just for demonstration 
try: 

    try: 
     # call your library code that can raise `Key empty` Exception 
     raise Exception('Key empty') 
    except Exception as e: 
     # if exception occurs, we will check if its 
     # `Key empty` and raise our own exception 
     if str(e) == 'Key empty': 
      raise KeyEmptyException() 
     else: 
      # else raise the same exception 
      raise e 
except Exception as e: 
    # we will finally check what exception we are getting 
    print('Caught Exception', e) 
+0

但LIB是不是我的控制之下。它是開源的,所以我可以編輯它,但我最好試着在不編輯庫的情況下捕捉它。這不可能嗎? – kramer65

+0

我甚至會選擇RuntimeError作爲基類。 – Gribouillis

+0

如果庫引發的異常是固定的。然後你必須捕捉到這個例外。您可以捕獲該異常並提出您自己的異常作爲回報。 –

1

你需要繼承Exception

class EmptyKeyError(Exception): 
    pass 

try: 
    raise EmptyKeyError('Key empty') 
except EmptyKeyError as exc: 
    print(exc) 
except Exception: 
    print('caught the general exception')