-2

When using specific classes in java, why am I seemingly forced to supply exception handling for certain classes in java api?

such as :

private DocumentBuilderFactory dbf =  DocumentBuilderFactory.newInstance();
private DocumentBuilder db;

    try {
        db = dbf.newDocumentBuilder();
    } catch(Exception e) {}

Will compile, but :

private DocumentBuilderFactory dbf =  DocumentBuilderFactory.newInstance();
private DocumentBuilder db;


        db = dbf.newDocumentBuilder();

Will not. Why? Could some one please clarify this for me? Can I not just let the possible exception affect my program at runtime without handling it?

TheEllo
  • 39
  • 4

2 Answers2

2

Because Java has checked exceptions. Which means the compiler is going to require you to either catch the exception or advertise that your method can potentially throw the exception that an invoked method can throw.

This particular method can throw a ParserConfigurationException.

You don't have to catch it, but if you don't then you do have to advertise this fact on your method. For example:

private void myMethod() throws ParserConfigurationException

This tells consuming code that it needs to be prepared to potentially catch and handle the exception.

It's another argument entirely whether or not checked exceptions is a good thing. The internet has no shortage of debate on the subject. But that's not something the compiler is going to care about :)

Also note that, while this compiles:

try {
    db = dbf.newDocumentBuilder();
} catch(Exception e) {}

an empty catch block is a famously bad idea. It means you're catching the exception, but you're not meaningfully handling it. The two are very different things.

David
  • 208,112
  • 36
  • 198
  • 279
0

The Oracle website answers my question at: http://docs.oracle.com/javase/tutorial/essential/exceptions/catchOrDeclare.html

TheEllo
  • 39
  • 4