Question

    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?

Was it helpful?

Solution

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top