Java Exceptions: throw clause

You have seen that an exception is thrown either implicitly in the try block and there is a catch block ready to handle it. But, there are methods, which throw the exception, but do not catch it within the method body. In this case the method which is throwing the exception must use a throws clause with its definition. The throws clause acts as warning message which makes the calling module aware that the called module is throwing an exception. In case of runtime exception, the method that leaves them unhandled need not use throws clause, the runtime environment will handle them.

Consider the following class structure that has a method, namely, method_one ( ). This method is using the throws clause which is throwing an exception object. Note that in the same method there is no subsequent catch clause. This method is being called from the main ( ) method which in turn is made to catch the exception thrown by method_one( ), though main ( ) is not responsible for throwing it directly. Now if the main ( ) method is not handling this exception it can now specify a throws clause and let the exception be handle by the runtime environment.

publicstaticvoid main (String args []){try{ method_one ();// main ( ) is not throwing the// exception, but it has to catch// it}catch(<exception_one> object){// Statement for exception handling}}}

Consider the following example, which has two static methods: throwExcp ( ) and the main ( ) method. The throwExcp ( ) method throws the object of exception IllegalAccessException (this exception is thrown when you try to access a class for which you do not have the permission) and catches it. But note the catch block, inside which object of exception IllegalAccessException is thrown again, and this time it not caught by any subsequent block of throwExcp( ). When you try to compile the program, you receive an error message.

Throws_clause.java:12: unreported exception java.lang.IllegalAccessException; must be caught or declared to be thrown
throw new IllegalAccessException( );
^
1 error

Take a look at the modified version of the same program. In the definition of the function throwExcp ( ) itself a throws clause is added which warns the caller function that the called function is throwing an exception, but it is not handling it. The complier now would let the function throwExcp ( ) go without handling the exception, but in turn, demands the caller function, i.e., main ( ) to handle the exception. So the main ( ) function despite not throwing the exception directly, has to handle it.

Thus, throws clause basically provides a broader design scope, wherein the originator is not handling the exception in it’s own way, but allowing the exception to be handled differently by different methods calling it.