What happens if a method throws an exception that was not specified in the method declaration with "throws"
Asked Answered
C

6

25

I've never used the "throws" clause, and today a mate told me that I had to specify in the method declaration which exceptions the method may throw. However, I've been using exceptions without problems without doing it, so, why is it needed if, in fact, it's needed?

Christopherchristopherso answered 3/2, 2011 at 17:50 Comment(2)
You're only forced to specify exceptions that are checked (and that's really annoying). When you fail to do so the compiler should complain.Simply
I voted to leave this question open because it and the answers give a good coverage of throw with checked and unchecked exceptions.Mycah
R
27

Java has two different types of exceptions: checked Exceptions and unchecked Exceptions.

Unchecked exceptions are subclasses of RuntimeException and you don't have to add a throws declaration. All other exceptions have to be handled in the method body, either with a try/catch statement or with a throws declaration.

Example for unchecked exceptions: IllegalArgumentException that is used sometimes to notify, that a method has been called with illegal arguments. No throws needed.

Example for checked exceptions: IOException that some methods from the java.io package might throw. Either use a try/catch or add throws IOException to the method declaration and delegate exception handling to the method caller.

Rebbeccarebe answered 3/2, 2011 at 18:3 Comment(1)
'throws' keyword helos to delegate exception handling to other components. See video demo: bitspedia.com/2013/11/how-to-delegate-exception-handling.htmlAlternative
O
14

If a method is declared with the throws keyword then any other method that wishes to call that method must either be prepared to catch it or declare that itself will throw an exception.

For instance if you want to pause the application you must call Thread.sleep(milliseconds);

But the declaration for this method says that it will throw an InterruptedException

Declaration:

public static void sleep(long millis) throws InterruptedException

So if you wish to call it for instance in your main method you must either catch it:

public static void main(String args[]) {
    try {
        Thread.sleep(1000);
    } catch(InterruptedException ie) {
        System.out.println("Opps!");
    }
}

Or make the method also declare that it is throwing an exception:

public static void main(String args[]) throws InterruptedException {
    Thread.sleep(1000);
}
Oribelle answered 3/2, 2011 at 18:4 Comment(2)
in you're last example, how does i catch the exception?Disarmament
@somefolk In my last example the program will not catch the InterruptedException because the throws is on the main() function. If one occurs then the program will abruptly end.Oribelle
U
7

It can happen, even with checked exceptions. And sometimes it can break logging.

Suppose a library method uses this trick to allow an implementation of Runnable that can throw IOException:

class SneakyThrowTask implements Runnable {

    public void run() {
        throwSneakily(new IOException());
    }

    private static RuntimeException throwSneakily(Throwable ex) {
        return unsafeCastAndRethrow(ex);
    }

    @SuppressWarnings("unchecked")
    private static <X extends Throwable>X unsafeCastAndRethrow(Throwable ex) throws X {
        throw (X) ex;
    }

}

And you call it like this:

public static void main(String[] args) {
    try {
        new SneakyThrowTask().run();
    } catch (RuntimeException ex) {
        LOGGER.log(ex);
    }
}

The exception will never be logged. And because it's a checked exception you cannot write this:

public static void main(String[] args) {
    try {
        new SneakyThrowTask().run();
    } catch (RuntimeException ex) {
        LOGGER.log(ex);
    } catch (IOException ex) {
        LOGGER.log(ex); // Error: unreachable code
    }
}
Unmentionable answered 3/2, 2011 at 19:4 Comment(1)
But would you ever write such code? Just wondering under what situation might one want to write such codeSuccuss
A
4
  1. You need to declare checked exceptions that your method throws.
  2. If you declare 'throws Exception' that pretty much covers most if not all checked exceptions
  3. You can always throw an unchecked runtime exception and not have to declare.

Im pretty sure if you try to throw a checked exception, and haven't declared the method as throwing that type, the code wont even compile (checking now).

EDIT, right so if you try something simple like

public static void main(String[] args) {
   throw new Exception("bad");
}

you get a compile error.

Specifically for your question, if you invoke a method that is declared to throw Exception(s) you must either try/catch the method invocation, or declare that your method throws the exceptions.

Aerodontia answered 3/2, 2011 at 17:55 Comment(1)
The problem was that I didn't know that there were checked and unchecked exceptions. I would accept your answer if it wasn't because Andreas_D gave me the perfect answer. Thanks!Christopherchristopherso
B
3

The throws key word is used to throw an exception to another method.

It eases the handle exception to the user. Because then all of the exceptions can be handled in a method which is used to run.

Mostly it is mainly a method, so that the user does not need to explore inside the method.

It also throws keyword force to the compiler to handle the exception which could be occurring.

If you were a API developer, when you write a code, you might see that an exception could occur, so you use the throws keyword to handle it when the method runs.

Bribery answered 23/6, 2018 at 1:48 Comment(0)
K
2

Java throws keyword,

  • Java throws keyword is used to declare an exception.
  • throws is followed by class.
  • Checked exception can be propagated with throws.
  • It provides information to the caller of the method about the exception.

throws example,

void m()throws ArithmeticException{  
    //method code  
}  
Krummhorn answered 25/6, 2018 at 7:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.