I'm trying to load a PNG file into a BufferedImage like so:

BufferedImage image = ImageIO.read(new File("smile.png"));

When I use this line of code alone, it produes the error:

Unhandled Exception Type IOException...

I can fix this by surrounding the statement with try/catch like so:

BufferedImage image = null;
try
{
    image = ImageIO.read(new File("smile.png"));
}
catch (IOException e)
{
    System.out.println(e);
}

My question is, do you always have to handle IOExceptions when using ImageIO.read()? if so, then why and are there any other classes that do this? I've done a lot of research on the internet and couldn't find a definative answer.

Thanks :)

If your method calls a method that can throw an IOException (like ImageIO.read does), you either need to catch the exception or declare that your method may throw an IOException too (which you do by adding throws IOException to your method's signature).

You have to do this because IOException is a checked exception and the Java compiler ensures that each method may only throw those checked exceptions that it's been declared to throw using the throws declaration.

The idea behind this is that you're always aware if there's a possible error condition that you do not handle.

And yes, there are other methods in other classes that throw checked exceptions, too. Pretty much all IO-related methods can throw IOExceptions. And there of course are other checked exceptions as well that need to be handled the same way.

Thanks, that makes perfect since.

Is there any way that I can tell which exceptions are checked and which are unchecked? I've been using the Java Standard Edition API as a reference when programming, but it doesn't explain which exceptions are checked and which aren't

Thanks again :)

An unchecked exception is one that inherits (directly or indirectly) from RuntimeException. A checked exception is one that doesn't.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.