2013-06-13 36 views
17

Cân nhắcLàm cách nào tôi có thể dễ dàng loại bỏ các ngoại lệ trước đây khi tôi đưa ra ngoại lệ của riêng mình để phản hồi?

try: 
    import someProprietaryModule 
except ImportError: 
    raise ImportError('It appears that <someProprietaryModule> is not installed...') 

Khi chạy, nếu someProprietaryModule không được cài đặt, người ta thấy:

(traceback data) 
ImportError: unknown module: someProprietaryModule 

During handling of the above exception, another exception occurred: 

(traceback data) 
ImportError: It appears that <someProprietaryModule> is not installed... 

Có lẽ tôi không muốn "Trong quá trình xử lý của ngoại lệ ở trên ..." dây chuyền (và các dòng trên nó) xuất hiện. Tôi có thể làm điều này:

_moduleInstalled = True 
try: 
    import someProprietaryModule 
except ImportError: 
    _moduleInstalled = False 
if not _moduleInstalled: 
    raise ImportError('It appears that <someProprietaryModule> is not installed...') 

Nhưng điều đó giống như một chút hack. Tôi có thể làm gì khác?

+0

này có thể giúp http://stackoverflow.com/questions/1319615/proper-way-to-declare-custom-exceptions- in-modern-python –

Trả lời

26

Trong Python 3.3 và sau đó raise ... from None có thể được sử dụng trong trường hợp này.

try: 
    import someProprietaryModule 
except ImportError: 
    raise ImportError('It appears that <someProprietaryModule> is not installed...') from None 

Điều này có kết quả mong muốn.

+0

Vừa mới đăng bài tương tự. Xem thêm [PEP3134] (http://www.python.org/dev/peps/pep-3134/). – Aya

+1

[PEP 409] (https://docs.python.org/3.3/whatsnew/3.3.html#pep-409-suppressing-exception-context) là những gì được thêm vào cú pháp 'từ None'. –

0

Điều này có thể được thực hiện như thế này trong Python 2.7 và Python 3:

try: 
    import someProprietaryModule 
except ImportError as e: 
    raised_error = e 

if isinstance(raised_error, ImportError): 
    raise ImportError('It appears that <someProprietaryModule> is not installed...')