outofmind outofmind - 2 years ago 57
Java Question

Java is there a difference between declaring throws Exception and declaring which exceptions are thrown?

Final edit due to this question having been marked as duplicate: this question is about the semantics of the

declaration - the question which is this said to be a duplicate of handles different aspects of
and none of those 15 answers there gave me the insight of the chosen answer here. Anyway - so let's keep it here as a duplicate.

In Java you have to declare a
clause and name the exceptions that this method could throw - so the easy way is to just declare

void myMethod(...) throws Exception

or you could be more specific and for example state

void myMethod(...) throws SQLException, NamingException

in case the method may just throw these two.

I understand that it makes a difference whether in a try/catch block I

try { ... } catch (Exception exc) { ... }


try { ... } catch (SQLException | NamingException exc) { ... }

because the first will also catch a
, the second won't - so this is a difference.

But is there also any difference in declaring
throws Exception
throws SQLException, NamingException
concerning the semantics of the program? The second may be more readable, but I don't see any other difference. Is there any?

Answer Source

But is there also any difference in declaring throws Exception vs. throws SQLException, NamingException

The difference is:

  • if you declare throws SQLException, NamingException the compiler assures that you have catched exactly these two exceptions. Otherwise you will get a Unhandled exception type ... error.

  • On the other hand, if you declare throws Exception, the compiler assures that you have catched Exception.

In the second case, you can still catch any other exception which inherits from Exception without getting a compiler error (like "Exception ... never thrown"). However, you must either catch Exception itself or add the throws Exception to the calling method to allow passing the exception further upwards. For example,

private void someMethod() throws Exception {
    throw new NumberFormatException("Illegal number format");

If this method gets called, you can catch the NumberFormatException, but you also have to either handle the more generic Exception or declare it in the throws clause (and then handle it further up in the call hierarchy):

public void myMethod() {
    try {
    }catch(NumberFormatException nfe) {
    }catch(Exception ex) {


public void myMethod() throws Exception {
    try {
    }catch(NumberFormatException nfe) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download