Coming from C#, I just don't get this 'throws exception' that is written after a class/method definition:
public void Test() throws Exception
Do you have to write this? What if you don't? If I call a method that has this symbol, do I have to catch it?
The throws keyword in Java is used to declare exceptions that can occur during the execution of a program. For any method that can throw exceptions, it is mandatory to use the throws keyword to list the exceptions that can be thrown.
The throw statement throws a user-defined exception. Execution of the current function will stop (the statements after throw won't be executed), and control will be passed to the first catch block in the call stack. If no catch block exists among caller functions, the program will terminate.
The caller has to handle the exception using a try-catch block or propagate the exception. We can throw either checked or unchecked exceptions. The throws keyword allows the compiler to help you write code that handles this type of error, but it does not prevent the abnormal termination of the program.
You don't have to write it in all cases -- you just have to write it if your method throws a checked Exception
(an exception that is a subclass of Exception
and not a subclass of RuntimeException
). This is because your method signature is a contract, and it's declaring to all the code which calls it that it has the potential for throwing the given exception. Because it's a checked exception -- an exception which can be anticipated -- the calling code needs to anticipate the potential of seeing the exception thrown, and needs to be able to handle it.
To answer your two specific questions:
bar
can throw SomeException
, and method foo
calls bar
and doesn't want to catch the exception, the method signature for foo
would declare that it too throws SomeException
.The Exceptions chapter of the Java lessons is very good at explaining this in detail, and JavaWorld has a good article about throwing and catching exceptions that I've always found to be a good reference to pass onto folks.
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