Showing posts with label exception. Show all posts
Showing posts with label exception. Show all posts

Friday, 13 January 2012

Exception Wrapping for persistence

Data can be stored in various ways, for example:
  • a relational database
  • text files
  • on the web (for example, fetching the weather forecast from a web site)
If the storage method changes, then the low level Exception objects thrown by the data access layer can also change. For example, when the data store is moved from text files to a relational database, IOException is replaced with SQLException. Otherwise there will be compilation errors throughout the code.

Removing the compilation point of view, lets look at the design point. Then consider a typical J2EE application that has a simple web layer, a business layer and a database layer. If some SQL query in the database layer goes completely wrong I will get an SQLException of some sort. In your point of view the web application (being the topmost layer) will catch this exception in the end.

This defeats the entire purpose of having a multitier (3+) architecture. I'm now dependent on the database layer in the web layer, because all exceptions are thrown all the way upwards.

The point of the PersistenceException is that it keeps the tiers independent from each other, except for the tier beneath it. The web layer doesn't care if it's an SQLException. It only needs to know something went wrong with the business logic, and more specifically with the persistence of business data objects.

In any case, the 'business code' knows more of what to do than the layers above it. If it can't do anything meaningful with it, you can either log it or perform some other action. The question is: what would a layer above it (eg. the web layer) know more of what to do than the business layer?

Exceptions Methods

 ollowing is the list of important medthods available in the Throwable class.
SNMethods with Description
1public String getMessage()
Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor.
2public Throwable getCause()
Returns the cause of the exception as represented by a Throwable object.
3public String toString()
Returns the name of the class concatenated with the result of getMessage()
4public void printStackTrace()
Prints the result of toString() along with the stack trace to System.err, the error output stream.
5public StackTraceElement [] getStackTrace()
Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack.
6public Throwable fillInStackTrace()
Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace.

Effective Java Exception handling

1. Use checked exceptions when you know that or you can recover  from the exception without any side affects.
2. The best use of exceptions is to translate exception in the calling method to the exception which is more appropriate for it and you should let the cause of the exception flow from the called methods to the calling methods.
For this you should have one of the constructors of your Exception classes like
 1: // Exception with chaining-aware constructor
 2:   class HigherLevelException extends Exception {
 3:       HigherLevelException(Throwable cause) {
 4:           super(cause);
 5:       }
 6:   }
You can also use the Throwable.initCause method for this if you don’t have the constructor like the one above.
3. Don’t use the 2nd point too much if the lower level method can get away with the exception, then you should do that. Don’t overload the calling methods too much to handle the exceptions thrown by the lower methods.
4. If you are declaring your own exception class you can always include some methods or attributes which can be used to convey more about the exception when it occurs.
5. Try to reuse exceptions (comes generally when you are creating your own API). The most reusabel exceptions are
IllegalArgumentException, IllegalStateException, NullPointerException, IndexArrayOutOfBounds and some more.
6. Most importantly, use Exceptions only for Exceptional conditions. Don’t write your logic which is based on exceptions. For example, don’t do like this
 1: // wrong usage of exception handling
 2: try {
 3:     someObject.someMethod();
 4: } catch (NullPointerException npe)
 5: {
 6:     // other code
 7: }
7. If rather than Exception you can have state testing method before actually using a state-dependent method like checking iterator.hasNext() before executing the iterator.next() method is more appropriate.
8. All of the unchecked throwables you implement should subclass  RuntimeException (directly or indirectly).
9. Use runtime exceptions to indicate programming errors. The great majority of runtime exceptions indicate precondition violations. A precondition violation is simply a failure by the client of an API to adhere to the contract established by the API specification. For example, the contract for array access specifies that the array index must be between zero and the array length minus one. ArrayIndexOutOfBoundsException indicates that this precondition was violated.
10. Always declare checked exceptions individually, and document precisely the conditions under which each one is thrown using the Javadoc @throws tag. Don’t take the shortcut of declaring that a method throws some superclass of multiple exception classes that it can throw. As an extreme example, never declare that a method “throws Exception” or, worse yet, “throws Throwable.”
11.Use the Javadoc @throws tag to document each unchecked exception that a method can throw, but do not use the throws keyword to include unchecked exceptions in the method declaration.  It is important that the programmers using your API be aware of which exceptions are checked and which are unchecked, as their responsibilities differ in these two cases. The documentation    generated by the Javadoc @throws tag in the absence of the method header generated by the throws declaration provides a strong visual clue to help the programmer distinguish checked exceptions from unchecked.
12. If an exception is thrown by many methods in a class for the same reason, it is acceptable to document the exception in the class’s documentation comment rather than documenting it individually for each method. A common example is NullPointerException. It is fine for a class’s documentation comment to say, “All methods in this class throw a NullPointerException if a null object reference is passed in any parameter,” or words to that effect.
13. To capture the failure, the detail message of an exception should contain the values of all parameters and fields that “contributed to the exception. You must write the toString() method of your exception carefully.
14. Failure Atomicity(Object remains in consistence state after a failure)-
ways to achieve failure atomicity:
a. A closely related approach to achieving failure atomicity is to order the computation so that any part that may fail takes place before any part that modifies the object.
b. This approach is a natural extension of the previous one when arguments cannot be checked without performing a part of the computation.
c. A third and far less common approach to achieving failure atomicity is to write recovery code that intercepts a failure that occurs in the midst of an operation and causes the object to roll back its state to the point before the operation began. This approach is used mainly for durable (disk-based) data structures.
d.A final approach to achieving failure atomicity is to perform the operation on a temporary copy of the object and to replace the contents of the object with the temporary copy once the operation is complete. This approach occurs naturally when the computation can be performed more quickly  once the data has been stored in a temporary data structure. For example, Collections.sort dumps its
input list into an array prior to sorting to reduce the cost of accessing elements in the inner loop of the sort. This is done for performance, but as an added benefit, it ensures that the input list will be untouched if the sort fails.
As a rule, any generated exception that is part of a method’s specification should leave the object in the same state it was in prior to the method invocation. Where this rule is violated, the API documentation should clearly indicate what state the object will be left in.
15. An empty catch block defeats the purpose of exceptions, which is to force you to handle exceptional conditions. At the very
least, the catch block should contain a comment explaining why it is appropriate to ignore the exception.

Sunday, 9 October 2011

Divide by Zero in case of Java

One of the good interview questions I found was related to divide by zero.
Lets take the case:

What will be the output of this code snippet?

public class NaN {

public static void main(String[] args) {
double d = 2.0 / 0.0;
System.out.println(d);
}
}

What's the answer: The code will not compile or will it throw a DivideByZero error? Both are wrong. The code compiles fine and the output is,
Infinity

Let's check another code snippet,

public class NaN {

public static void main(String[] args) {
double d = 0.0 / 0.0;
System.out.println(d);
}
}

The output in this case is,
NaN

Monday, 4 July 2011

Do not return in a finally block: return will swallow your exceptions

I was recently working on a code, which was failing without giving any exception. So I had to add lots of logging to the code, to see where is the bug. I caught nothing via this method.
So I decided to check out the module source code and yeah finally I found it while debugging. The module was correctly implementing what was required and generating the required Exception as expected.

The author, unfortunately, forgot one of the rules of the Java Language and was returning from a finally block, effectively discarding the exception that was launched just a couple of lines before.

That's amazing how many times I see people returning from a finally block without understanding what the code is intended to do.

Still not convinced?

Run this:
@Test
public void hello() {
try {
throw new UnsupportedOperationException();
} finally {
return;
}
}

No exception is thrown. Surprised? You should not. There are plenty of variations of this theme out there. Nevertheless, if you're still surprised that the hello() method completes without throwing an UnsupportedOperationException, please read on.

try/catch/finally blocks

According to the Java Language Specification, this is a simplified vision of what happens during the execution of a finally block (you can read the normative documentation here):
  • If the finally block completes normally, then the try statement completes abruptly for reason R.
  • If the finally block complete abruptly for reason S, then the try statement completes abruptly for reason S.
As you may notice in the JLS, then, the "reason" a try statement completes with will always be affected by an abrupt completion of a finally block. Said in other words, the finally block will "decide" what happens later.

You probably though many times about what happens if an exception is thrown in a finally block, don't you? Perhaps you even tested that case: the exception that will be propagated up the stack will be the exception launched in the finally block. That's not surprising, after all, and that's why you should carefully check that the code in finally blocks don't fail without control.

So far, so good. But what happens, then, when a return statement is executed inside a finally block?

The return statement

What Java programmers often misunderstand is the very nature of a return statement. The Java Language Specification is clear about that:

The return statement always completes abruptly.

That's why exceptions launched in try or catch blocks (the "reason" of their abrupt completion) are simply ignored and not relaunched when a finally block completes abruptly with a return statement, being that the "resulting" reason of the abrupt completion of the try statement, as seen in the previous section.

Lesson learned

I personally don't see any good reason, unless you want any exception to be swallowed, to return in a finally block: it defies the very reason for try/catch blocks to exist.

Do think twice (or more...) before using this construct: chances are you're doing a favor to others and yourself if you avoid it.

Sunday, 3 July 2011

java.lang.NoClassDefFoundError in java

This is normally a CLASSPATH problem. Try resetting the CLASSPATH, and/or make sure all third party JAR's are actually present in the correct locations. In some rare cases you will get this problem when the JVM has problems loading a third party jar due to version incompatibilities.

To set classpath in java, just see how to reset it. Following links may be useful to read:

Monday, 27 June 2011

More precise exception rethrow

The more precise rethrow is a tricky one to understand. See if you can spot what the new feature is in the example below. Will it compile on pre-java-7? If not how would it need to be changed to compile on pre-java-7? The answers lie after the example.


public class MorePreciseExceptionRethrow {

static class Exception1 extends Exception {}
static class Exception2 extends Exception {}

public static void main(String[] args) throws Exception1, Exception2 {
try {
boolean test = true;
if (test) {
throw new Exception1();
} else {
throw new Exception2();
}
} catch (Exception e) {
throw e;
}
}

}


On Java 6 compiling the above gives the following exception.
Foo.java:18: unreported exception java.lang.Exception; must be caught or declared to be thrown
throw e;
^
1 error

This can be fixed for Java 6 by changing:
public static void main(String[] args) throws Exception1, Exception2 {

to:

public static void main(String[] args) throws Exception {{

So now you see the improvement that Java 7 offers with this feature. You can be more precise in the declaration of the exceptions that you rethrow. Very nice indeed.

try-with-resources statement


This is simply beautiful and incredibly reassuring for the simple reason that resource closing is not only automatic and requires a lot less code but if in the examples below multiples exceptions are thrown (i.e. one in the closing of the resource and one in the use of the resource) then not only does the latter not get swallowed (unlike pre-java-7) but finally you can access all suppressed exceptions (i.e. the former) via the new API.


public class TryWithResources {

static class MyResource1 implements AutoCloseable {
@Override
public void close() throws Exception {
System.out.println("MyResource1 was closed!");
}
}

static class MyResource2 implements AutoCloseable {
@Override
public void close() throws Exception {
System.out.println("MyResource2 was closed!");
}
}

public static void main(String[] args) throws Exception {
/*
         * close() methods called in opposite order of creation
         */
try (MyResource1 myResource1 = new MyResource1();
MyResource2 myResource2 = new MyResource2()) {}
}

}


NOTE: In the above example the resources are closed in an order opposite to their order of creation.

Multi catch in Exceptions


The multi-catch is very useful indeed and significantly reduces the number of lines of code to do such things from before.


public class MultiCatchException {

static class Exception1 extends Exception {}
static class Exception2 extends Exception {}

public static void main(String[] args) {
try {
boolean test = true;
if (test) {
throw new Exception1();
} else {
throw new Exception2();
}
} catch (Exception1 | Exception2 e) {
}
}

}

Friday, 24 June 2011

Remember to properly close the File!

Today few comments on how to deal with Files, Streams, Connections and anything else that is ‘closeable’ in Java. To simplify we will focus on a FileWriter class and a simple code snippet with a bug that uses it:

public void writeToFile(String fileName, String content) {
try {
FileWriter file = new FileWriter(fileName);
file.write(content);
} catch (IOException e) {
// Log the exception
}
}

So what’s wrong? Well, plenty of things: we do not check the input values (maybe they are null or rubbish?), we do not care whether the file existed or is a directory, we do not care about specifying the encoding for the file. On the other hand you could argue that all of this are not problems but ‘features’, that the contract of this method says: just write using a FileWriter. That may be, but still there is one thing wrong with this code – we did not close the file.

Is that important? Well, yeah! Not closing the file may result in corrupted output of your write and makes the system still occupy the resources that could be freed. Always remember to close your Files, Streams, Connections! Let’s make a quick fix to the code and remove the bug:

public void writeToFile(String fileName, String content) {
try {
FileWriter file = new FileWriter(fileName);
file.write(content);
file.close();
} catch (IOException e) {
// Log the exception
}
}

Fixed? I guess some of you think it is fixed, but in fact it is not – what if there is an exception thrown during the write? The method will exit and the file will not be closed! Okay, there is a fix for that – use try/finally clause. This will guarantee that no matter what will happen in write the file will be closed.

public void writeToFile(String fileName, String content) {
FileWriter file = null;
try {
file = new FileWriter(fileName);
file.write(content);
} catch (IOException e) {
// Log the exception
} finally {
file.close();
}
}

Fixed? Well… no. The exception can be also thrown in the FileWriter constructor, so in finally block the file will be null. And this will result in NullPointerException. Let’s deal with that:

public void writeToFile(String fileName, String content) {
FileWriter file = null;
try {
file = new FileWriter(fileName);
file.write(content);
} catch (IOException e) {
// Log the exception
} finally {
if (file != null) {
file.close();
}
}
}

Done? Not yet… file.close() also can throw an exception! Since the method writeToFile does not allow any checked exception to be thrown, we have to deal with that also:

public void writeToFile(String fileName, String content) {
try {
FileWriter file = new FileWriter(fileName);
try {
file.write(content);
} finally {
file.close();
}
} catch (IOException e) {
// Log the exception
}
}

Finally (pun intended) we are done and the bug is fixed! Notice that in this code we did not had to check whether file is null before closing it – this is because the only way file is null is if an exception was thrown in the constructor in line 3 and this would lead to skipping most of the code and going to line 10. As you can see closing a closeable object is not a trivial task, so remember to do it properly!

There is another issue appearing in this problem – readability. If this the code above seems readable to you, then try to imagine dealing with more than one closeable object – it can get really messy! Therefore whenever you work with closeable objects it is a good idea to split the code into 2 methods: one that deals with exceptions and closing and the other which just does the main code. To see how this would work with the code above take a look at the following:

// Here we handle opening the file and manage exceptions.
public void writeToFile(String fileName, String content) {
try {
FileWriter file = new FileWriter(fileName);
try {
performWriteToFile(file, content);
} finally {
file.close();
}
} catch (IOException e) {
// Log the exception
}
}

// Here we perform all the operations on the file.
// This method usually is much longer.
private void performWriteToFile(FileWriter file,
String content) throws IOException {
file.write(content);
}


Monday, 13 June 2011

The Callable Interface

One of the beautiful things about Java from its very first release was the ease with which we could write multi-threaded programs and introduce asynchronous processing into our designs. The Thread class and Runnable interface combined with Java’s memory management model meant for straightforward thread programming.

The run() method in Runnable cannot return a result (i.e. it returns void) and cannot throw a checked exception. If you try to throw an exception in a run() method, the javac compiler insists that you use a throws clause in the method signature. However, the superclass run() method doesn't throw an exception, so javac will not accept this. The lack of thrown checked exceptions was a little more serious.

Even if you were careful and you stored these for later verification, you couldn’t force all uses of the class to check the exception. You could go through all your getters and throw the Exception if it existed on each one. Besides being cumbersome, even that wasn’t foolproof. You couldn’t enforce calls to any of these. Thread programmers would correctly call join() to wait for it complete and may then have gone on their merry way.

The new java.util.concurrent.Callable interface is much like Runnable but overcomes two drawbacks with Runnable.
The interface looks like this :
public interface Callable<V> {
V call() throws Exception;
}


Implementing Runnable to get returned value
If you need a result from a Runnable task, you have to provide some external means of getting that result. A common technique is to set an instance variable in the Runnable object and provide a method to retrieve that value. For example,

public MyRunnable implements Runnable
{
private int fResult = 0;
public void run () {
...
fResult = 1;
} // run

// A getter method to provide the result of the thread.
public int getResult () { return fResult; }

} // class MyRunnable


Even if you were careful and you stored these for later verification, you couldn’t force all uses of the class to check the exception. You could go through all your getters and throw the Exception if it existed on each one. Besides being cumbersome, even that wasn’t foolproof. You couldn’t enforce calls to any of these. Thread programmers would correctly call join() to wait for it complete and may then have gone on their merry way.
Implementing the Callable
The Callable interface solves these problems. Instead of a run() method the Callable interface defines a single call() method that takes no parameters but is allowed to throw an exception. A simple example is

import java.util.concurrent.*;
public class MyCallable implements Callable
{
public Integer call () throws java.io.IOException {
return 1;
}
} // MyCallable

This call() method returns an Integer. (Note that we have conveniently used the autoboxing support in J2SE 5.0 to have the literal int 1 value automatically boxed into an Integer return value.)

Note
The call() method is the entry point into a Callable object, and it's return type is the type parameter set in the Callable object. To implement Callable with no return value, use Callable<void>. Also, note that the call() method throws a checked exception, as compared to the run() method in Runnable which does not throw any exception. The Executors class contains utility methods to convert from other common forms to Callable classes. However, Callable cannot be used in place of a Runnable. Callable objects have to be invoked by ExecutorService. The Executor framework provides the Future interface to allow handling the cancellation and returns of a Callable object.

Getting the return value from a Callable depends upon the new generics feature:

FutureTask task = new FutureTask (new MyCallable ());
ExecutorService es = Executors.newSingleThreadExecutor ();
es.submit (task);
try {
int result = task.get ();
System.out.println ("Result from task.get () = " + result);
}
catch (Exception e) {
System.err.println (e);
}
es.shutdown ();

Here, we use the FutureTask class that supports an Integer return value. Then the task is submitted using the ExecutorService submit() method, and the result is obtained from the FutureTask get() method, again using auto-unboxing to convert the Integer to an int. See the API documentation for more information on ExecutorService, and FutureTask.

 

Callable Example


CallableImpl.java


package com.vaani.callable;

import java.util.concurrent.Callable;

public class CallableImpl implements Callable<Integer> {

private int name;
public CallableImpl(int i){
name = i;
}

public Integer call() {
for(int i = 0; i < 10; i++) {
System.out.println("Thread : " + getName() + " I is : " + i);
}
return new Integer(getName());

}

public int getName() {
return name;
}

public void setMyName(int myName) {
this.name = myName;
}

}

CallableDemo.java



public class CallableDemo {

public static void main(String[] args) {
Callable<Integer> callable = new CallableImpl(2);

ExecutorService executor = new ScheduledThreadPoolExecutor(5);
Future<Integer> future = executor.submit(callable);

try {
System.out.println("Future value: " + future.get());
} catch (Exception e) {
e.printStackTrace();
}
}
}

Also we have future which is similar to Callable except Future represents the result of an asynchronous computation. But it is discussed here.







Download the source


Source code can be downloaded from here.

Saturday, 11 June 2011

How to force the subclasses of a concrete class to override a method?

There is no such real world scenario where a concrete entity will want to force a more specific entity to override its method. If it is to be overridden then why not make the super class as abstract.

Anyways, the logic behind the interview questions being asked now a days is something which requires best talent from the psychology field.

Solution: The solution which I have come up with for the above Java Interview question is to use the instanceof operator in the super class and throw an exception if the instance on which method is being invoked is found to be of the sub class. The sample program showing this scenario follows:

Though still its not like generating compile time error but gives exception at runtime.  Do suggest if you have a better solution.

public class Test{

void test() {
if ((this instanceof Test1)) {
throw new RuntimeException();
}
System.out.println("passed");
}

public static void main(String[] args) {
Test t1 = new Test();
Test1 t2 = new Test1();

t1.test();
t2.test();
}

}
class Test1 extends Test {

}

The output of above program is:
passed
Exception in thread "main" java.lang.RuntimeException
at Test.test(Test.java:5)
at Test.main(Test.java:15)

Wednesday, 25 May 2011

Common Class Loading Issues (java)

  • ClassNotFoundException
    • Thrown when an application tries to explicitly load a class using class name string and class (.class file) is not found in the classpath.
      Eg. Thrown when an application tries to load a class through its string name using:
      • The forName method in Class.
      • The findSystemClass method in ClassLoader.
      • The loadClass method in ClassLoader.

      By throwing a ClassNotFoundException, the class loader informs us that the bytecode required to define the class is not present in the locations where the class loader is looking for it. There may be classes in a system that cannot be seen by a class loader. This is because a class loader only sees classes that are loaded by itself or loaded by class loaders to which it has a reference. In the class loading delegation model, the classes that are visible to a class loader are those that are loaded by itself or loaded by its parent – in other words, a class loader cannot look down.
    • Can be easily checked by enabling verbose:class JVM argument

  • NoClassDefFoundError
    • Thrown if the ClassLoader instance tries to implicitly load in the definition of a class and no definition of the class could be found.
      The searched for class definition existed when the currently executing class was compiled but the definition can no longer be found. Essentially this means that a NoClassDefFoundError is thrown as a result of a unsuccessful implicit class load.
  • ClassCastException
    • Thrown as a result of incompatible types being found in a type comparison. It indicates that the code has attempted to cast an object to a subclass of which it is not an instance. (remember ClassLoader Namespace)
    • Two classes of the same fully qualified name are not equal to each other if they are loaded by different ClassLoaders. They cannot be cast to each other and such operations would result in a ClassCastException
  • UnsatisfiedLinkError
    It occurs during the resolving stage of the linking phase when a program tries to load an absent or misplaced native library.
  • ClassCircularityError
    It is thrown if a class if a class or interface could not be loaded because it would be its own superclass or superinterface.
  • ClassFormatError
    • This exception is thrown during the verification stage of the linking phase of class loading. The binary data can be malformed if the bytecodes have been changed --if the major or minor number has been changed, for instance. This could occur if the bytecodes had been deliberately hacked, for example, or if an error had occurred when transferring the class file over a network.
    • The only way to fix this problem is to obtain a corrected copy of the bytecodes, possibly by recompiling.


Tuesday, 17 May 2011

Arrays and exceptions in java

Some common array programming mistakes are:
Runtime error: Forgetting that array subscripts start with zero. OR Going out of bound
Compile-time error: Writing a.length() instead of a.length. The length() method is used with Strings, not arrays.
Compile-time error: Declaring an array with a size. Eg, int[100] a; instead of int[] a = new int[100];.

Naming Conventions for Exceptions in java

It's good practice to append the word "Exception" to the end of all classes that inherit (directly or indirectly) from the Exception class. Similarly, classes that inherit from the Error class should end with the string "Error".

Adding custom exception to your Project Design

When you design a package of Java classes that collaborate to provide some useful function to your users, you work hard to ensure that your classes interact well together and that their interfaces are easy to understand and use. You should spend just as much time thinking about and designing the exceptions that your classes throw.

Thinking of Exceptions


Suppose you are writing a linked list class that you're planning to distribute as freeware. Among other methods, your linked list class supports these methods:
objectAt(int n)
Returns the object in the nth position in the list.
firstObject
Returns the first object in the list.
indexOf(Object n)
Searches the list for the specified Object and returns its position in the list.

What Can Go Wrong?

Because many programmers will be using your linked list class, you can be assured that many will misuse or abuse your class and its methods. Also, some legitimate calls to your linked list's methods may result in an undefined result. Regardless, in the face of errors, you want your linked list class to be as robust as possible, to do something reasonable about errors, and to communicate errors back to the calling program. However, you can't anticipate how each user of your linked list class will want the object to behave under adversity. So, often the best thing to do when an error occurs is to throw an exception.
Each of the methods supported by your linked list might throw an exception under certain conditions, and each method might throw a different type of exception than the others. For example,

objectAt
Throws an exception if the integer passed into the method is less than 0 or larger than the number of objects currently in the list.
firstObject
Throws an exception if the list contains no objects.
indexOf
Throws an exception if the object passed into the method is not in the list.

But what type of exception should each method throw? Should it be an exception provided with the Java development environment? Or should you roll your own?

Choosing the Exception Type to Throw

When faced with choosing the type of exception to throw, you have two choices:
  1. Use one written by someone else. The Java development environment provides a lot of exception classes that you could use.
  2. Write one of your own.
You should go to the trouble of writing your own exception classes if you answer "yes" to any of the following questions. Otherwise, you can probably get away with using someone else's:
  • Do you need an exception type that isn't represented by those in the Java development environment?
  • Would it help your users if they could differentiate your exceptions from those thrown by classes written by other vendors?
  • Does your code throw more than one related exception?
  • If you use someone else's exceptions, will your users have access to those exceptions? A similar question is: Should your package be independent and self-contained?

Your linked list class can throw multiple exceptions, and it would be convenient to be able to catch all exceptions thrown by the linked list with one exception handler. Also, if you plan to distribute your linked list in a package, all related code should be packaged together. Thus for the linked list, you should roll your own exception class hierarchy.
The following diagram illustrates one possible exception class hierarchy for your linked list:

LinkedListException is the parent class of all the possible exceptions that can be thrown by the linked list class. Users of your linked list class can write a single exception handler to handle all linked list exceptions with a catch statement like this:

catch (LinkedListException ex) {. . . }

Or, users could write more specialized handlers for each subclass of LinkedListException.



Choosing a Superclass


The diagram above does not indicate the superclass of the LinkedListException class. As you know, Java exceptions must be Throwable objects (they must be instances of Throwable or a subclass of Throwable). So, your temptation might be to make LinkedListException a subclass of Throwable. However, the java.lang package provides two Throwable subclasses that further divide the type of problems that can occur within a Java program: Errors and Exceptions. Most of the applets and applications that you write will throw objects that are Exceptions. (Errors are reserved for serious hard errors that occur deep in the system.)


Theoretically, any Exception subclass could be used as the parent class of LinkedListException. However, a quick perusal of those classes show that they are either too specialized or completely unrelated to LinkedListException to be appropriate. Thus, the parent class of LinkedListException should be Exception.
Because runtime exceptions don't have to be specified in the throws clause of a method, many packages developers ask: "Isn't it just easier if I make all of my exception inherit from RuntimeException?" The answer to this question is covered in detail on Runtime Exceptions--The Controversy. The bottom line is that you shouldn't subclass RuntimeException unless your class really is a runtime exception! For most of you, this means "No, your exceptions shouldn't inherit from RuntimeException."

Monday, 16 May 2011

throw vs throws in java

throws is used to specify that an exception/s can be thrown. Specifying is more pertinent to checked exceptions.

throw is simply the statement to manually/programically throw the exception or any object of throwable type.

Using throws

a method, and then tell that this method throws following exception…and then write da .. da .. da. Eg.

public void myMethod() throws MalformedURLException,MyCustomException1
{
//do something in method
}



Using throw


throw just throws exception. Eg.

if(something)
throw someObjectOfThrowableType

Is the finally Statement Really Necessary in java?

At first the need for a finally statement may not be immediately apparent. Programmers often ask "Is the finally statement really necessary or is it just sugar for my Java?" In particular, C++ programmers doubt the need for a finally statement because C++ doesn't have one.The need for a finally statement is not apparent until you consider the following: how does the PrintWriter in the writeListmethod get closed if you don't provide an exception handler for the ArrayIndexOutOfBoundsException and anArrayIndexOutOfBoundsException occurs? (It's easy and legal to omit an exception handler for ArrayIndexOutOfBoundsExceptionbecause it's a runtime exception and the compiler won't alert you that the writeList contains a method call that might throw one.) The answer is that the PrintWriter does not get closed if an ArrayIndexOutOfBoundsException occurs and writeList does not provide a handler for it--unless the writeList provides a finally statement.
There are other benefits to using the finally statement. In the writeList example it is possible to provide for cleanup without the intervention of a finally statement. For example, you could put the code to close the PrintWriter at the end of the try block and again within the exception handler for ArrayIndexOutOfBoundsException, as shown here:

try {
. . .
out.close(); // don't do this; it duplicates code
} catch (ArrayIndexOutOfBoundsException e) {
out.close(); // don't do this; it duplicates code
System.err.println("Caught ArrayIndexOutOfBoundsException: " + e.getMessage());
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
}

However, this duplicates code, making the code hard to read and prone to errors if you modify the code later. For example, if you add code to the try block that may throw a new type of exception, you will have to remember to close thePrintWriter within the new exception handler (which if you're anything like me, you are bound to forget).


Catching Multiple Exception Types with One Handler in java

Consider the following code here, which has to deal with 2 exceptions. Now to handle this exception, we have to apply 2 catch blocks to handle the exception which we have shown here.

The two exception handlers used by the writeList method are very specialized. Each handles only one type of exception. The Java language allows you to write general exception handlers that handle multiple types of exceptions.As you know, Java exceptions are Throwable objects; they are instances of Throwable or a subclass of Throwable. The Java packages contain numerous classes that derive from Throwable and thus, build a hierarchy of Throwable classes. We have discussed the hierarchy here.

Your exception handler can be written to handle any class that inherits from Throwable. If you write a handler for a "leaf" class (a class with no subclasses), you've written a specialized handler: it will only handle exceptions of that specific type. If you write a handler for a "node" class (a class with subclasses), you've written a general handler: it will handle any exception whose type is the node class or any of its subclasses.Let's modify the writeList method once again. Only this time, let's write it so that it handles both IOExceptions andArrayIndexOutOfBoundsExceptions. The closest common ancester of IOException and ArrayIndexOutOfBoundsException is the Exceptionclass. An exception handler that handles both types of exceptions looks like this:

try {
. . .
} catch (Exception e) {
System.err.println("Exception caught: " + e.getMessage());
}

The class is pretty high in the Throwable class hierarchy. So in addition to the IOException and ArrayIndexOutOfBoundsExceptiontypes that this exception handler is intended to catch, it will catch numerous other types. Generally speaking, your exception handlers should be more specialized. Handlers that can catch most or all exceptions are typically useless for error recovery because the handler has to determine what type of exception occurred anyway to determine the best recovery strategy. Also, exception handlers that are too general can make code more error prone by catching and handling exceptions that weren't anticipated by the programmer and for which the handler was not intended.


How java implements Exception handling?

When an unexpected error occurs in a method, java has to handle this exception. So it has to throw that exception and handle it some way. Lets see how :

 

Throwing an exception

Many kinds of errors can cause exceptions--problems ranging from serious hardware errors, such as a hard disk crash, to simple programming errors, such as trying to access an out-of-bounds array element. When such an error occurs within a Java method, the method creates an exception object and hands it off to the runtime system. The exception object contains information about the exception, including its type and the state of the program when the error occurred. The runtime system is then responsible for finding some code to handle the error. In Java terminology, creating an exception object and handing it to the runtime system is called throwing an exception.

 

Catching an exception

After a method throws an exception, the runtime system leaps into action to find someone to handle the exception. The set of possible "someones" to handle the exception is the set of methods in the call stack of the method where the error occurred. The runtime system searches backwards through the call stack, beginning with the method in which the error occurred, until it finds a method that contains an appropriate exception handler. An exception handler is considered appropriate if the type of the exception thrown is the same as the type of exception handled by the handler. Thus the exception bubbles up through the call stack until an appropriate handler is found and one of the calling methods handles the exception. The exception handler chosen is said to catch the exception.
If the runtime system exhaustively searches all of the methods on the call stack without finding an appropriate exception handler, the runtime system (and consequently the Java program) terminates.