Friday, January 2, 2009

How to write Exceptions in Java?

Quick Question: How will you define your own exception?

Answer: You have to extend the Exception Class and write it like this.

Class MyException extends Exception
{
MyException() {
super();
}

MyException(String message) {
super(message);
}
}


If someone asks you this and you give the above answer, making him/her happy – immediately assume that you will be in the company of “Javaphiles” (my term for useless Java programmers and for decent ones – “Javaites”).

If he has scratched Java (2 books max!), then some more useless questions like, what are checked, unchecked exceptions or can I extend Throwable class or can I catch Object in the “Exception” clause or give me some example of Exception, etc.

When I stated off, exception was the coolest topic, as it was the easiest! But then, in due course of time, some new things came up, which are marvels. Here are some of the things which you should know about exceptions.

Rule Number – 1

Write useful exceptions and give handle to the data being found via the exception class, if you can.

Do NOT write exception classes for the sake of writing exceptions (and sometimes making your code throughput look larger than others!). Here is a way to write a good exception:

public class OutOfRangeException extends IllegalArgumentException {

private final long value, minVal, maxVal;

public OutOfRangeException(long value, long minVal, long maxVal) {
super("Value " + value + " is out of range: " + minVal + ".." + max +);
this.value = value;
this.min = minVal;
this.max = maxVal;
}

public long getValue() {
return value;
}

public long getMinValue() {
return minVal;
}

public long getMaxValue() {
return maxVal;
}
}


Rule Number – 2

Use Chained Exceptions, if you think that the main cause of error can be something else.

Say you are reading an integer value via IO and IO error occurred. In this case, it is very likely that we will the integer value to have a default value of “0”, and hence we will get the ArithmeticException. But, was it the real reason? NO. Ideally, you should have informed about the IOException.

For it, you can use the initCause(Throwable causeExce) method. Here, you can pass the IOException object when it is caught. When the calling method, which only catches the ArithmeticException, there it will print the actual cause of exception as well.

Rule Number – 3

Never extend directly from the Throwable class unless your application is at major layer boundaries.

By extending Throwable, you are giving hook for RuntimeException, which is not detected by the compiler and as an application developer you will not want an unchecked exception. Extending throwable, as I mentioned, has its own usage. Like if you have app server, you will want to ensure that the server can NOT be brought down by some unchecked exceptions. Here, you may want to use the extension of Throwable.

Rule Number – 4

If you have opened up any resource or URL or anything, close it only in the “finally” clause.

If you happen to put them in the Exception clause, it will only be executed if there is an exception, otherwise NOT! However, “finally” block will be executed, no matter what happens (with an “exit” statement also). It is there for this purpose only.

Rule Number – 5

Be careful while using Assertions.

Do not confuse Assertion with Exception handling, though Assertion uses Exception handling mechanism of Java via AssertionError class.

Exception = to have robust software program
Assertion = to have correct programs
Exception + Assertion = reliable program

You should use Assertion thinking that it will be handled like Exception. There is very good chance that Assertion can be disabled during production environment. Say your code uses assertions like below:

assert xxx.callAMethod();

It will have disastrous consequences if assertion is disabled in production environment. In fact, you should write code this way.

Rule Number – 6

Throw Exception early and catch exceptions late.

Whenever you believe that there is a possibility of exception will be thrown, throw them as early as possible. Your code flow should not wait for long to throw the exception.

Similarly while catching exceptions, the reverse is true, reason being that you may not have all the information to catch the exception and inform and hence it is better to wait till you have all the information.

Rule Number – 7

Always document your exception.

It is very important to note under what condition the exception will be thrown and why it was placed like that. Exceptions are very critical during debugging and your document will help a lot for your own debugging.

Rounding Up:

Rounding up, the same question as asked in the beginning – how will you write your own exception?

This should be your answer - if you answer it very simply.

Class MyException extends Exception
{
MyException() {
super();
}

MyException(String message) {
super(message);
}

MyException(String message, Throwable cause) {
super(message, cause);
}

MyException(Throwable cause) {
Super(cause);
}
}

There will be new methods with Throwable as parameter. For best possible reasons for having Throwable as a cause in the Exception class, you may have a look here.

http://www.teleox.com

0 comments:

Post a Comment