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?
When a method declares that it throws an exception, it is not required to handle the exception. The caller of a method that throws exceptions is required to handle the exceptions (or throw them to its caller and so on) so that the flow of the program can be maintained.
What happens if an exception is not caught? If an exception is not caught (with a catch block), the runtime system will abort the program (i.e. crash) and an exception message will print to the console. The message typically includes: name of exception type.
If a method throws an exception, and the exception is not caught inside the method, then the method invocation: Answers: terminates.
The throw keyword in Java is used to explicitly throw an exception from a method or any block of code. We can throw either checked or unchecked exception. The throw keyword is mainly used to throw custom exceptions.
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.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With