3

Final edit due to this question having been marked as duplicate: this question is about the semantics of the throws declaration - the question which is this said to be a duplicate of handles different aspects of throws 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 throws 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) { ... }

or

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

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

But is there also any difference in declaring throws Exception vs. 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?

outofmind
  • 1,430
  • 1
  • 20
  • 37
  • 2
    I would do whatever you believe is clearer. I prefer specific Exceptions however once the list gets to more than 5 I wonder if it really is clearer. – Peter Lawrey Apr 18 '16 at 08:25
  • 1
    as a user of this method - wouldn't I be forced to catch the RuntimeExceptions too? So I'd have to check for RuntimeExceptions in the catch-block and specific exceptions with 'instanceof', no? – Rhayene Apr 18 '16 at 08:29
  • @AndreasFester - this question here is about the semantics - the other just asks about whether it's good practice or not - it doesn't handle if it makes any semantic difference - and that's what I was asking – outofmind Apr 18 '16 at 08:45
  • @outofmind but if I call that foo.myMethod() I have to handle Exception. Which could also include some RuntimeExceptions that I may have no knowledge of. – Rhayene Apr 18 '16 at 09:29
  • @Rhayene ok, misunderstood your comment when I first read it - you're right, if I declare `throws Exception` I can't just catch *my* exception but will also catch `RuntimeException` automatically – outofmind Apr 18 '16 at 18:55

4 Answers4

2

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 {
        someMethod();
    }catch(NumberFormatException nfe) {
        nfe.printStackTrace();
    }catch(Exception ex) {
        ex.printStackTrace();
    }
}

Or:

public void myMethod() throws Exception {
    try {
        someMethod();
    }catch(NumberFormatException nfe) {
        nfe.printStackTrace();
    }
}
Andreas Fester
  • 36,091
  • 7
  • 95
  • 123
  • ok, so if `myMethod` would handle the NumberFormatException it would be done and doesn't have to throw anything, but when `someMethod` isn't specific in declaring just `throws NumberFormatException` then `myMethod` will have to take care of catching a never existing `Exception` or to declare `throws Exception` though it won't ever `throw` one - good point, thanks – outofmind Apr 18 '16 at 08:53
  • 1
    Yes, basically thats it - to be pedantic, a `NumberFormatException` **is** an `Exception`, just a more specific one. And, to be honest, `NumberFormatException` is probably a bad example since it is a `RuntimeException` so it is an unchecked exception. But in this example it should not make a difference (besides that `someMethod` would not require any `throws` clause at all) – Andreas Fester Apr 18 '16 at 09:06
1

Yes, there is a difference.

When you use the throws declaration of an exception in a method, you do it so you can handle it later (using try{}catch blocks).

When you handle the exception, you might just do the e.printStackTrace(), but that's not really handling it.

Instead, imagine you want to tell your user "You didn't introduce a number, please correct this mistake" and prompt them to introduce a number. You can do this if you throw NumberFormatException in the method you use to read. But if you throw just Exception, you can't know for sure if that was the error or any other exception, and you might have unexpected behaviours because of that.

dquijada
  • 1,697
  • 3
  • 14
  • 19
  • 1
    The question is not about **throwing** the exception, but about the method signature specifying `someMethod() throws Exception` versus `someMethod() throws NumberFormatException`. In either case, you could throw a `NumberFormatException` – Andreas Fester Apr 18 '16 at 08:23
  • I know. And the answer is about that too. If you do `throws Exception` you can't catch specific exceptions (unless you ALSO add a catch for _Exception_ that you will never use). – dquijada Apr 18 '16 at 08:26
0

The difference between two approach lies based on Exception Handling. For example, if you like to handle all exception in same way then, you should opt for first approach. On the other hand, if you like to deal different exception in different manner, you must go for second approach

Moosa
  • 79
  • 1
  • 2
  • 12
0

I would prefer to mention the exceptions explicitly in the function declaration after the throws keyword because then I know how I should handle these exceptions if they occur in the calling code. See the code below for better understanding..

public static void exceptionExample() throws SQlException, NamingException {

    }   

public static void main(String[] args) throws SQlException, NamingException {

    try {
        exceptionExample();
        exceptionExample();
    }
    catch(SQlException e){  
        System.out.println("Sql exception has occured");
    }
    catch(NamingException e){
        System.out.println("Naming Exception has occured");
    }   

  } 
  • If I would not have mentioned throws SQlException , NamingException explicitly in the function and have used only throws Exception then it implies I do not know which exception may occur. In that case in the catch() {...} block I would have used e.printStackTrace which is not really an efficient method of exception handling because user may never know what happened to the application. But here as you can see that I can inform the user that the respective exception has occurred which makes my application more user friendly.

  • Also Throwing Exception causes the calling code to catch the exceptions which they may not want to handle depending upon the application and all kinds of reasons.

So I would say it depends upon the wit of the programmer on how he/she wants to handle the exceptions efficiently.....

Aditya kumar
  • 76
  • 1
  • 11