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?
What happens if a method throws an exception that was not specified in the method declaration with "throws"
43.8k views Asked by bluehallu AtThere are 6 answers
- You need to declare checked exceptions that your method throws.
- If you declare 'throws Exception' that pretty much covers most if not all checked exceptions
- 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.
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);
}
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
}
}
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.
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 thejava.io
package might throw. Either use a try/catch or addthrows IOException
to the method declaration and delegate exception handling to the method caller.