Letting an Exception be Thrown to the Method Caller

Contact Us or call 1-877-932-8228
Letting an Exception be Thrown to the Method Caller

Letting an Exception be Thrown to the Method Caller

A method that generates an exception can be written to not catch it. Instead it can let it be thrown back to the method that called it.

The possibility that a method may throw an exception must be defined with the method.

[modifiers] returnType functionName(arguments)
		throws ExceptionClassName {
	body including risky code

Then an instance of ExceptionClassName or a class that extends it may be thrown so, stating that a method throws Exception is about as generic as you can get (stating that it throws Throwableis as generic as you can get, but not recommended). A method can throw more than one type of exception; in which case you would use a comma-separated list of exception types.

In this way, the method is now marked as throwing that type of exception, and a code that calls this method will be obligated to handle it.

When you extend a class and override a method, you cannot add exceptions to the throws list, but a base class method can list exceptions that it does not throw in the expectation that an overriding method will throw the exception. This is another example of the "inheritance cannot restrict access" principle we saw earlier.

If main() throws an exception, the JVM, which runs under Java rules, will handle the exception (by printing a stack trace and closing down the offending thread. In a single-threaded program, this will shut down the JVM).