Search

Useful Links

Monday, February 1, 2010

Throw and Throws in Java

Is it compulsory to use the finally block ?
It is always a good practice to use the finally block. The reason for using the finally block is, any unreleased resources can be released and the memory can be freed. For example while closing a connection object an exception has occurred. In finally block we can close that object. Coming to the question, you can omit the finally block when there is a catch block associated with that try block. A try block should have at least a catch or a finally block.

How are try, catch and finally block organized ?
A try block should associate with at least a catch or a finally block. The sequence of try, catch and finally matters a lot. If you modify the order of these then the code won’t compile. Adding to this there can be multiple catch blocks associated with a try block. The final concept is there should be a single try, multiple catch blocks and a single finally block in a try-catch-finally block.

What is a throw in an Exception block ?
"throw” is used to manually throw an exception (object) of type Throwable class or a subclass of Throwable. Simple types, such as int or char, as well as non-Throwable classes, such as String and Object, cannot be used as exceptions. The flow of execution stops immediately after the throw statement; any subsequent statements are not executed.

throw ThrowableInstance; ThrowableInstance must be an object of type Throwable or a subclass of Throwable.
throw new NullPointerException(“thrownException”);

What is the use of throws keyword ?
If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception. You do this by including a throws clause in the method’s declaration. A throws clause lists the types of exceptions that a method might throw.

type method-name(parameter-list) throws exception-list {
// body of method
}

Here, exception-list is a comma-separated list of the exceptions that a method can throw.

static void throwOne() throws IllegalAccessException {
System.out.println(“Inside throwOne.”);

No comments:

Post a Comment