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

Sunday, October 9, 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, July 4, 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.

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, June 27, 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, June 24, 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);
}


Wednesday, June 22, 2011

Exception transformer pattern

Checked exceptions are widespread in Java. Imagine the situation where you are calling numerous methods on a class (say for the sake of serving as an example: a service class) each of which throws a checked exception (say ServiceException).
class Service {

    static class ServiceException extends Exception {}

    void serviceMethod1() throws ServiceException {}
    void serviceMethod2() throws ServiceException {}

}

Client with repetitive error handling logic
Your class as a client now has to deal with this exception every time you call a service method and also for every different method you call.
public class Client {

    private Service service;

    void callServiceMethod1Normally() {
        try {
            service.serviceMethod1();
        } catch (ServiceException e) {
            throw new RuntimeException("calling service method 1 failed", e);
        }
    }

    void callServiceMethod2Normally() {
        try {
            service.serviceMethod2();
        } catch (ServiceException e) {
            throw new RuntimeException("calling service method 2 failed", e);
        }
    }

}


Exception transformer abstraction

However your exception handling strategy may be the same across your use of the service class only with a different message each time. Instead of repetitively duplicating your exception handling logic (try/catch) around every service call you can abstract this out as follows. The following class abstracts the logic out. Note that this class is only shown as a separate class for the purposes of incrementally describing the pattern. For best effect this class should ideally be contained within your client class as a static inner class.

public abstract class ExceptionTransformer {

    abstract void call() throws ServiceException;

    void transform(String message) {
        try {
            call();
        } catch (ServiceException e) {
            throw new RuntimeException(message, e);
        }
    }

}
New client using exception transformer

Now using the new exception transformer our exception handling logic is simplified to only the logic that differs between the client methods.

class ClientUsingExceptionTransformer {

    private Service service;

    void callServiceMethod1UsingTransformer() {
        new ExceptionTransformer() {
            @Override
            void call() throws ServiceException {
                service.serviceMethod1();
            }
        }.transform("calling service method 1 failed");
    }

    void callServiceMethod2UsingTransformer() {
        new ExceptionTransformer() {
            @Override
            void call() throws ServiceException {
                service.serviceMethod2();
            }
        }.transform("calling service method 2 failed");
    }

}


Variation

This pattern can be easily varied to suit your personal exception handling styles. Here’s another variation where different checked exceptions are thrown by different service methods and handled by only logging them this time.

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

class ClientWithVariations {

    static final Logger logger = LoggerFactory.getLogger(ClientWithVariations.class);

    static class Service {

        static class ServiceHungry extends Exception {}
        static class ServiceSleepy extends Exception {}

        void hungryMethod() throws ServiceHungry {}
        void sleepyMethod() throws ServiceSleepy {}

    }

    private Service service;

    void callHungryMethod() {
        new ExceptionTransformer() {
            @Override
            void call() throws Exception {
                service.hungryMethod();
            }
        }.transform("method was too hungry to respond :(");
    }

    void callSleepyMethod() {
        new ExceptionTransformer() {
            @Override
            void call() throws Exception {
                service.sleepyMethod();
            }
        }.transform("method was too sleepy to respond :(");
    }

    static abstract class ExceptionTransformer {

        abstract void call() throws Exception;

        void transform(String message) {
            try {
                call();
            } catch (Exception e) {
                logger.error(message, e);
            }
        }

    }

}

This pattern really shows its value most effectively when you have numerous methods using it and also when there are multiple checked exceptions to handle resulting in multiple catch blocks all over the place.
Do you have any exception handling API patterns of your own? I know Joshua Bloch has suggested a few in Effective Java of which one comes to mind – an exception throwing method can be transformed into a boolean via another method which just returns false in the catch block and true elsewhere that can be quite useful if you don’t want to pollute the rest of the code with knowledge of this handling logic. By the way, before anyone mentions this I’m not suggesting converting checked exceptions to runtime exceptions or suppressing them by logging them is always the right thing to do. Thanks for reading.
P.S. This pattern will be particularly nice with closures in Java 8. And the multicatch in Java 7 will certainly also help make code more concise.

Tuesday, June 14, 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.

Sunday, June 12, 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, May 25, 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.


Wednesday, May 18, 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];.

Tuesday, May 17, 2011

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."

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.

Types of exceptions in java

All exceptions in Java are subclasses of the built-in-class called Throwable. There are two main subclasses under throwable: Exception and Error.

This can be seen in this figure:

exceptionHierarchy

 

See here for checked, unchecked and Error in detail in java.

Monday, May 16, 2011

Advantage of using exceptions to handle errors in java

By using exceptions to manage errors, Java programs have the following advantages over traditional error management techniques:


Advantage 1: Separating Error Handling Code from "Regular" Code

In traditional programming, error detection, reporting, and handling often lead to confusing spaghetti code. For example, suppose that you have a function that reads an entire file into memory. In pseudo-code, your function might look something like this:
readFile {
open the file;
determine its size;
allocate that much memory;
read the file into memory;
close the file;
}
At first glance this function seems simple enough, but it ignores all of these potential errors:


  • What happens if the file can't be opened?

  • What happens if the length of the file can't be determined?

  • What happens if enough memory can't be allocated?

  • What happens if the read fails?

  • What happens if the file can't be closed?
To answer these questions within your read_file function, you'd have to add a lot of code to do error detection, reporting and handling. Your function would end up looking something like this:

errorCodeType readFile {
initialize errorCode = 0;
open the file;
if (theFileIsOpen) {
determine the length of the file;
if (gotTheFileLength) {
allocate that much memory;
if (gotEnoughMemory) {
read the file into memory;
if (readFailed) {
errorCode = -1;
}
} else {
errorCode = -2;
}
} else {
errorCode = -3;
}
close the file;
if (theFileDidntClose && errorCode == 0) {
errorCode = -4;
} else {
errorCode = errorCode and -4;
}
} else {
errorCode = -5;
}
return errorCode;
}
Java provides an elegant solution to the problem of error management: exceptions. Exceptions enable you to write the main flow of your code and deal with the, well, exceptional cases elsewhere. If your read_file function used exceptions instead of traditional error management techniques, it would look something like this:


readFile {
try {
open the file;
determine its size;
allocate that much memory;
read the file into memory;
close the file;
} catch (fileOpenFailed) {
doSomething;
} catch (sizeDeterminationFailed) {
doSomething;
} catch (memoryAllocationFailed) {
doSomething;
} catch (readFailed) {
doSomething;
} catch (fileCloseFailed) {
doSomething;
}
}


Advantage 2: Propagating Errors Up the Call Stack


A second advantage of exceptions is the ability to propagate error reporting up the call stack of methods. Suppose that the readFile method is the fourth method in a series of nested method calls made by your main program: method1 callsmethod2, which calls method3, which finally calls readFile.


method1 {
call method2;
}
method2 {
call method3;
}
method3 {
call readFile;
}
Suppose also that method1 is the only method interested in the errors that occur within readFile. Traditional error notification techniques force method2 and method3 to propagate the error codes returned by readFile up the call stack until the error codes finally reach method1--the only method that is interested in them.

method1 {
errorCodeType error;
error = call method2;
if (error)
doErrorProcessing;
else
proceed;
}
errorCodeType method2 {
errorCodeType error;
error = call method3;
if (error)
return error;
else
proceed;
}
errorCodeType method3 {
errorCodeType error;
error = call readFile;
if (error)
return error;
else
proceed;
}
As you learned earlier, the Java runtime system searches backwards through the call stack to find any methods that are interested in handling a particular exception. A Java method can "duck" any exceptions thrown within it, thereby allowing a method further up the call stack to catch it. Thus only the methods that care about errors have to worry about detecting errors.

method1 {
try {
call method2;
} catch (exception) {
doErrorProcessing;
}
}
method2 throws exception {
call method3;
}

method3 throws exception {
call readFile;
}

However, as you can see from the pseudo-code, ducking an exception does require some effort on the part of the "middleman" methods. Any checked exceptions that can be thrown within a method are part of that method's public programming interface and must be specified in the throws clause of the method. Thus a method informs its callers about the exceptions that it can throw, so that the callers can intelligently and consciously decide what to do about those exceptions.
Note again the difference in the bloat factor and code obfuscation factor of these two error management techniques. The code that uses exceptions is more compact and easier to understand.


Advantage 3: Grouping Error Types and Error Differentiation



Often exceptions fall into categories or groups. For example, you could imagine a group of exceptions, each of which represents a specific type of error that can occur when manipulating an array: the index is out of range for the size of the array, the element being inserted into the array is of the wrong type, or the element being searched for is not in the array. Furthermore, you can imagine that some methods would like to handle all exceptions that fall within a category (all array exceptions), and other methods would like to handle specific exceptions (just the invalid index exceptions, please).
Because all exceptions that are thrown within a Java program are first-class objects, grouping or categorization of exceptions is a natural outcome of the class hierarchy. Java exceptions must be instances of Throwable or any Throwabledescendant. As for other Java classes, you can create subclasses of the Throwable class and subclasses of your subclasses. Each "leaf" class (a class with no subclasses) represents a specific type of exception and each "node" class (a class with one or more subclasses) represents a group of related exceptions.
For example, in the following diagram, ArrayException is a subclass of Exception (a subclass of Throwable) and has three subclasses.

InvalidIndexException, ElementTypeException, and NoSuchElementException are all leaf classes. Each one represents a specific type of error that can occur when manipulating an array. One way a method can exceptions is to catch only those that are instances of a leaf class. For example, an exception handler that handles only invalid index exceptions has a catch statement like this:

catch (InvalidIndexException e) {
. . .
}
ArrayException is a node class and represents any error that can occur when manipulating an array object, including those errors specifically represented by one of its subclasses. A method can catch an exception based on its group or general type by specifying any of the exception's superclasses in the catch statement. For example, to catch all array exceptions regardless of their specific type, an exception handler would specify an ArrayException argument:

catch (ArrayException e) {
. . .
}
This handler would catch all array exceptions including InvalidIndexException, ElementTypeException, andNoSuchElementException. You can find out precisely which type of exception occurred by querying the exception handler parameter e. You could even set up an exception handler that handles any Exception with this handler:

catch (Exception e) {
. . .
}
Exception handlers that are too general, such as the one shown here, can make your code more error prone by catching and handling exceptions that you didn't anticipate and therefore are not correctly handled within the handler. We don't recommend writing general exception handlers as a rule.
As you've seen, you can create groups of exceptions and handle exceptions in a general fashion, or you can use the specific exception type to differentiate exceptions and handle exceptions in an exact fashion.

Chitika