How do you handle exceptions and warnings in snappy?

What is the standard way to handle exceptions thrown by snappy?

My code looks like this:
try: sp = ProductIO.readProduct(filename) except ProductIO.readProduct.IOException as e: return e

I also tried this:
try: sp = ProductIO.readProduct(filename) except RuntimeWarning as w: return w

However I am not successfully getting exceptions with ProductIO.readProduct.IOException. What class I am supposed to be using for the exceptions from ProductIO.readProduct? I want to be able to get ERRORS and WARNINGS such as those below in the exception:

WARNING: org.esa.snap.core.dataio.dimap.DimapProductReader: DimapProductReader: Unable to read file ‘/home/web/satellite/tmp/Hartbeespoort/’ referenced by ‘solar_flux_band_21’.

Thanks in advance.

After a full day of searching python documentation, the snappy API documentation, stackoverflow, etc. I still cannot seems to get the warning generated by ProductIO.readProduct into a string that I can use, or turn the warning messages into an exception using python’s warnings module…

Hi Mark,

the following should work:

    product = ProductIO.readProduct(product_file)
except RuntimeError as e:

I’m not sure, but I think it will be RuntimeError in most cases, but you can also catch BaseException.

Thanks @marpet, that is the solution I have been using. However I was hoping to be able to catch Warnings and not just exceptions, however I haven’t found a way to do that yet. Thanks for answering this probably python more than snap question!

Hi, did you find a solution?

I am also looking for a way to capture warnings.

(I have a large number of images, and I’m trying to find which of them that are corrupt)

Warning can’t be caught. They are just logged to the command line.

OK - I found a way to achieve what I needed using bash, as you can then redirect the warnings to a text file using e.g. gpt Read file 2>>log.txt