简体   繁体   中英

How to catch specific Exception in Python?

I want to catch a specific exception and present a message rather than the exception raise and breaking the code.

The exception is:

The exception is: ICSharpCode.Decompiler.Metadata.PEFileNotSupportedException: PE file does not contain any managed metadata.

I know where in the code the exception raises and that I should wrap it with try-except. I don't know how to "Import" the specific exception and then use it properly in the code

I tried to build the exception like this:

class PEFileNotSupportedException(Exception):
    def __init__(self):
        super(PEFileNotSupportedException, self).__init__

and then import it and use it like that:

   try:
       os.system(command)
   except:
       raise PEFileNotSupportedException("The DDL of this type are NOT supported!!!")

But it is not working.

try:
  # your_code_here
except PEFileNotSupportedException:
  print('Your message here')

This should be what you are looking for, assuming you have imported PEFileNotSupportedException

With regards to importing the exception, it should be inside a module and you can import it with the "import" statement.

EDIT: from Module.Where.Your.Exception.Is import PEFileNotSupportedException

You could try and import the exception with:

from ICSharpCode.Decompiler.Metadata import PEFileNotSupportedException

try:
    do_something()
except PEFileNotSupportedException:
    print("Exception caught")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM