Throw and throws in Java exceptions

Difference between Throw and Throws

Exceptions can be generated by the Java run time system or they can be manually generated by our code. Manually generated exceptions are typically used to report some error condition to caller of the method. To manually throw an exception, we use the key word throws. Any exception that is thrown out of a method must be specified as such by a throw clause.

Throw

We have been catching exceptions that are thrown by the Java run-time system. However, it is possible for our program to throw an exception explicitly, using the throw statement.

==
Headline text

Exceptions are thrown by java run time System.The expections will caught by an immediatly encompassinf the try and catch block.
==


The throw keyword denotes a statement that causes an exception to be initiated. It takes the Exception object to be thrown as argument. The exception will be caught by an immediately encompassing try-catch construction or propagated further up the calling hierarchy.

A throwable instance is used with the key word throw. There are two ways from where we can obtain a throwable object i.e. using a parameter into catch clause, or creating one with the new operators.

throw new ThrowableInstance( );

The flow of execution stops immediately after the throw statement. The nearest enclosing try block is inspected to see if it has a catch statement that matches the type of the exception. If it does not find a match the control is transferred to next statement. If no matching catch is found, then the default the exception handler halts the program and prints the stack trace.

Throws

The difference between Runtime exception and non-Runtime exception is that a Runtime exception does not have to be caught, whilst a non-Runtime must be. Any action which throws an instance of a non-Runtime exception must do one of two things: it must either completely handle itself or it must indicate that the exception may be propagated from the action by including a throws clause in the header of the action.
If a method is capable of causing an exception that it does not handle, it must specify the behavior so that the callers of the method can guard themselves against that exception. You do this by including a throws clause in the method’s declaration. All exceptions that a method can throw must be declared in the throws clause. If they are not then a compile time error will result.

Exception Interception

In runtime engine environments such as Java (or .Net) there exist tools that attach to the runtime engine and everytime that an exception of interest occurs they record debugging information that existed in memory at the time the exception was thrown (stack and heap values). These tools are called Exception Interception or Error Interception tools and they provide 'root-cause' information for exceptions in Java programs that run in production, testing or development environments.
 
< Prev   Next >