0

Possible Duplicate:
Java unchecked/checked exception clarification

I have been reading about debates on checked vs unchecked exceptions in java, i know the difference but i am not fully clear how we can choose one over the other. Do we really have any options? doesn't java force us to use try catch in case there is a possibility of a checked exception. How do we implement an application using unchecked exceptions only, how do we take care of situations where there is a possibility of a checked exception for such application. If some one is kind enough to clear this up for me with some code sample on how to convert checked exceptions to unchecked exceptions that would be awesome :)

Community
  • 1
  • 1

2 Answers2

0

You don't have an option to change checked exceptions that are built into the libraries you use, including the JDK.

But you can wrap them and re-throw as unchecked if you wish. You minimize the effect to the scope of the method that has to try/catch it.

And you can have all the custom exceptions you create extend RuntimeException.

duffymo
  • 305,152
  • 44
  • 369
  • 561
0

Checked exceptions are meant to be thrown in situations that represent not unexpected behavior that should't happen (eg a division by 0) but situations which may arise and for in which the programmer should take care of managing them.

This is a design of Java language and Java API which works quite well because you always know what you are supposed to care about when using an API which provides functionality that can lead to special situations that you should handle.

I don't see the point of forget about checked exceptions, of course you can encapsulate everything that can raise an exception so that you manage internally what is happening and just throw an unchecked (custom) exception but you do have to care about these problems anyway.

The only safe approach I can see is something like:

class UncheckedFileNotFoundException extends RuntimeException {
  ..
}

class Foobar {
  public static void method(String path) {
    try {
      FileReader reader = new FileReader(path);
    }
    catch (FileNotFoundException e) {
      // code;
      throw new UncheckedFileNotFoundException();
    }
  }
}

But this doens't solve the problem: if the file is not found then the caller should do something accordingly and allowing him to just ignore the exception or hiding the fact that the method could throw one (because you don't have the commodity of throws FileNotFoundException in method signature) doesn't improve anything.

Jack
  • 131,802
  • 30
  • 241
  • 343