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/S3A_OL_1_EFR____20171015T075647_20171015T075947_20171015T100309_0179_023_206_3420_MAR_O_NR_002.SEN3_Hartbeespoort_subset.data/solar_flux_band_21.img’ 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:

try:
    product = ProductIO.readProduct(product_file)
except RuntimeError as e:
    print(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

2 Likes