문제

    try{
       IMAGE = ImageIO.read(getClass().getResource("Images/image.png"));
    }
    catch (IOException ex){
        JOptionPane.showMessageDialog(null, "<html>Error<br>Missing images</html>" ,"Error",JOptionPane.ERROR_MESSAGE);
        System.exit(1);
    }

The catch block is not working, I still get the default message:

Exception in thread "main" java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(Unknown Source)
at KPK.<init>(KPK.java:40)
at Main.main(Main.java:22)

How can I catch this exceptiont?

도움이 되었습니까?

해결책

  1. First and foremost, DON'T catch the IllegalArgumentException. This error suggests something very bad in your code, and shouldn't really be caught. See Jon Skeet's answer here for more on why this is bad. Instead you should:
  2. Separate the code in your line where you read your image.
  3. First get the URL from the getResource()
  4. Check if it's null
  5. If null don't call ImageIO.read(...) with it.
  6. You should learn and follow Java naming conventions so that others will better understand your code. For instance, don't capitalize non-constant variables.

i.e.,

try{
  URL imgUrl = getClass().getResource(IMAGE_PATH); // path should be a constant 
                                          // or variable, not a String literal
  if (imgUrl == null) {
    // show error and get the heck out of here
  } else {
    image = ImageIO.read(imgUrl);
  }
} catch (IOException ex){
  JOptionPane.showMessageDialog(null, "<html>Error<br>Missing images</html>" ,
       "Error",JOptionPane.ERROR_MESSAGE);
  System.exit(1);
}

다른 팁

catch (IOException | IllegalArgumentException ex)

Also, create an image first...Image im = null; then use the file... im = ImageIO.read(new File("YOUR IMAGE FILE PATH"));

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top