如何同时处理 IOException 和 IIOException

How to handle both IOException and IIOException at the same time

任何人都可以帮助我如何捕获 IOException 和 IIOException,因为我需要区分图像格式和图像加载错误。

像这样的东西不起作用,因为我没有捕获 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());
  }
}

你试过这样的事情吗

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());
        }
    }

这就是为什么我们有单独的 catch 语句:

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); }

例外情况需按具体顺序给出;即在你的情况下,

  catch (IIOException ex) { System.err.println("error 1 "+ex); }
  catch (IOException ex2) { System.err.println("error 2 "+ex2); }