2

Can anyone help me out how to catch both IOException and IIOException, because i need to differentiate image format and image load error.

Something like this is not working because i am not catching IOException.

catch (IIOException e)
{
  System.out.println("Invalid image format: " + e.getMessage());

  Throwable t = e.getCause();
  if ((t != null) && (t instanceof IOException)) {
    System.out.println("Unable to load image: " + e.getMessage());
  }
}
Andy Turner
  • 131,952
  • 11
  • 151
  • 228
caniaskyouaquestion
  • 627
  • 2
  • 11
  • 20
  • Note: `t instanceof IOException` returns false if `t == null` ([question](http://stackoverflow.com/questions/2950319/is-null-check-needed-before-calling-instanceof)), so you don't need to check that first. – Andy Turner May 19 '16 at 13:07

2 Answers2

3

Thats why we have separate catch statements:

try {

}
catch (ExceptionTypeA e1) { }
catch (ExceptionTypeB e2) { }


  try {
      bim=ImageIO.read(new File(....));
      int[] a={2, 2, 3,4 };
      a[7]=4;
  }
  catch (ArrayIndexOutOfBoundsException ex2) { System.err.println("error 2 "+ex2); }
  catch (Exception ex) { System.err.println("error 1 "+ex); }

Exceptions need to be given in order of specificity; i.e. in your case,

  catch (IIOException ex) { System.err.println("error 1 "+ex); }
  catch (IOException ex2) { System.err.println("error 2 "+ex2); }
gpasch
  • 2,748
  • 3
  • 9
  • 12
0

Have you tried something like this

catch(IOException e)
    {
        if(e instanceof IIOException)
        {
            System.out.println("Invalid image format: " + e.getMessage());
        }else
        {
            System.out.println("Unable to load image: " + e.getMessage());
        }
    }