-3

Assuming that the Exception we are throwing is checked, is it compulsory to add throws in a method declaration whenever we use throw inside the method?

Ardent Coder
  • 3,777
  • 9
  • 27
  • 53
user2627156
  • 151
  • 1
  • 3
  • 11

5 Answers5

3

Any checked exception (e.g., one which does not extend RuntimeException) that might escape a method needs to be declared in the method signature. For example:

public static void mightThrow(String s) throws NumberFormatException {
    // ...
    int x = Integer.parseInt(s);
    // ...
}

Even though we do not throw any exceptions directly, Integer.parseInt() might throw a checked NumberFormatException. Since we call that method, and we do not catch the potential exception, then our method must also declare the exeception in its throws signature.

This does not necessarily mean that every method that throws (or might throw) a checked exception must declare throws in its signature. If the thrown exception is always caught within that method, it need not be added to the signature. For example:

public static Integer tryParseInteger(final String s) {
    try {
        return Integer.parseInt(s);
    }
    catch (NumberFormatException ignored) {
        return null;
    }
}

In this example, we will always catch any NumberFormatException that might be thrown by Integer.parseInt() and prevent it from bubbling up the stack, so we do not need to declare it in our tryParseInteger() method.

Unchecked exceptions never need to be declared:

public static void unsupported() {
    throw new UnsupportedOperationException(
        "The specified operation is not supported."
    );
}

Here, because UnsupportedOperationException derives from the unchecked RuntimeException, it does not need to be declared.

Mike Strobel
  • 25,075
  • 57
  • 69
  • That means that: if we do our tests inside the method (for example if we test the condition that may cause the exception manualy (e.g if (arg = 0) throw dividebyzeroexception();) we don't need to add throws dividebybzeroexce in the header) ? – user2627156 Nov 20 '13 at 14:18
  • No, it means if you _catch_ the exception that gets thrown, such that it cannot bubble up the stack, then you do not need to declare it (e.g., `try { throw new Exception(); } catch (Throwable) {}`). But exceptions like `ArithmeticException` extend `RuntimeException`, so even if they escape the method, they need not be declared in the `throws` signature. – Mike Strobel Nov 20 '13 at 14:22
  • so this is correct: public boolean shutdown(int a,int b) { if (a – user2627156 Nov 20 '13 at 14:25
  • No, there you have a checked exception being thrown that always escapes the method (you never catch it yourself). It must be declared in the `throws` signature. – Mike Strobel Nov 20 '13 at 14:27
  • cool, thanks! i thought the (if (test) throw checkedException("aa!") can be considererd as, catching the exception). but it seems that the key word "catch " must be used :D – user2627156 Nov 20 '13 at 14:29
  • Correct. Also, if you rethrow the checked exception (or throw a new checked exception) _from within_ the `catch` block, you will still need to add the exception type to the `throws` signature (assuming it isn't caught by an outer `catch` block). – Mike Strobel Nov 20 '13 at 14:30
1

No, since you may want to throw a exception but handle it in the same place, aka method

Bogdan M.
  • 2,161
  • 6
  • 31
  • 53
0

The Throws simply let javac know that this method might cause this kind of exception. It is not always necessary. It's useful when you know that a specific method can throw some sort of exception.

TurnsCoffeeIntoScripts
  • 3,868
  • 8
  • 41
  • 46
0

Generally speaking, Java is exception-strict, so you have to specific what types of exceptions a method throws. Note that you can use inheritance to simplify your methods' signatures. E.g., you can declare your method as throws IOException, and within its implementation throw any type of IOException you want such as FileNotFoundExeption, InteruptedIOException, etc.

One exception (no pun intended) to this rule are RuntimeExceptions (such as OutOfMemoryError or UnsupportedOperationException) which can be thrown without having to declare them.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

Differences:

1) You can declare multiple exception thrown by method in throws keyword by separating them in common e.g. throws IOException, ArrayIndexBoundException etc, while you can only throw one instance of exception using throw keyword e.g. throw new IOException("not able to open connection").

2) throws keyword gives a method flexibility of throwing an Exception rather than handling it. with throws keyword in method signature a method suggesting its caller to prepare for Exception declared in throws clause, specially in case of checked Exception and provide sufficient handling of them. On the other hand throw keyword transfer control of execution to caller by throwing an instance of Exception. throw keyword can also be used in place of return as shown in below example:

 private static boolean shutdown() {
    throw new UnsupportedOperationException("Not yet implemented");
 }

as in below method shutdown should return boolean but having throw in place compiler understand that this method will always throw exception .

3) throws keyword cannot be used anywhere exception method signature while throw keyword can be used inside method or static initializer block provided sufficient exception handling as shown in example.

 static{
    try {
        throw new Exception("Not able to initialized");
    } catch (Exception ex) {
         Logger.getLogger(ExceptionTest.class.getName()).log(Level.SEVERE, null, ex);
    }
}

4) throw keyword can also be used to break a switch statement without using break keyword.

int number = 5;
 switch(number){
        case 1:
            throw new RuntimeException("Exception number 1");
        case 2:
            throw new RuntimeException("Exception number 2");
    }
Shoaib Chikate
  • 8,665
  • 12
  • 47
  • 70