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ā€¦

1 Like

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

Hey so I have a follow up question,

For context I am getting a ā€œ[Failed to Read Data for level 0 and rectangle]ā€ error from the API. Now the java exception isnā€™t my real issue. My issue is this ā€œsevereā€ warning or error or whatever it is from the API is not raising an Python exception and continues to execute the code.

Is there a way for me to explicitly set that all java exceptions should be converted into a python exception?