【问题标题】:How to handle both IOException and IIOException at the same time如何同时处理 IOException 和 IIOException
【发布时间】:2016-09-16 09:09:41
【问题描述】:

谁能帮我解决如何同时捕获 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());
  }
}

【问题讨论】:

  • 注意:如果t == null (question),t instanceof IOException 将返回 false,因此您无需先检查。

标签: java ioexception javax.imageio


【解决方案1】:

你有没有尝试过这样的事情

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

【讨论】:

    【解决方案2】:

    这就是为什么我们有单独的 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); }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-14
      • 2012-02-27
      • 2013-11-11
      相关资源
      最近更新 更多