[英]How to catch specific Exception in Python?
我想捕获特定的异常并显示一条消息,而不是引发异常并破坏代码。
例外是:
例外是: ICSharpCode.Decompiler.Metadata.PEFileNotSupportedException:PE 文件不包含任何托管元数据。
我知道异常在代码中的哪个位置引发,我应该用 try-except 包装它。 我不知道如何“导入”特定的异常,然后在代码中正确使用它
我试图建立这样的异常:
class PEFileNotSupportedException(Exception):
def __init__(self):
super(PEFileNotSupportedException, self).__init__
然后导入它并像这样使用它:
try:
os.system(command)
except:
raise PEFileNotSupportedException("The DDL of this type are NOT supported!!!")
但它不起作用。
try:
# your_code_here
except PEFileNotSupportedException:
print('Your message here')
这应该是你正在寻找的,假设你已经导入了 PEFileNotSupportedException
关于导入异常,它应该在一个模块内,您可以使用“import”语句导入它。
编辑: from Module.Where.Your.Exception.Is import PEFileNotSupportedException
您可以尝试使用以下方法导入异常:
from ICSharpCode.Decompiler.Metadata import PEFileNotSupportedException
try:
do_something()
except PEFileNotSupportedException:
print("Exception caught")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.