Exception Handling

0
753

As per Oracle specification – “An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program’s instructions.” Lets try and understand what are the unexplored facts behind this single sentence. Frankly speaking, Exceptions are bad. To provide more details around – It could be result of bad programming, bad data, bad resource expectation or may be bad resources. The only good thing in all these bad conditions is – we have option to handle them. I am not trying to prototype the things but my effort is to put the things in the way I see them. I will try to explain and map these bad things that could potentially cause exception or error with right terminologies being used in java world. But before diving into it let us see the exception class tree.

Exception

Unchecked Exception : Commonly known as RuntimeException. This is the exception caused because of bad programming or sometimes bad data. Example for this exception could be – NullPointerException, ArithmeticException, ClassCastException etc. When you compile your code, the compiler will never complain about such exceptions and let the code go to JVM for execution. It is easily understandable that e.g. NullPointerException could arise if you try to perform some operation on a null object. So, does it mean before performing any operation you have to put a null check? I would say NO. A null check must only be placed where potentially you could get a null object and is not desirable or in one of scenario you get a null object and you want to handle it. Otherwise, do not put a null check. Now here comes a tricky bit. If your code do not expect null object still you are getting this exception, it mean you are dealing with bad data and you need to correct it.

Checked Exception : These are exceptions designed to address bad expectation while execution of your java code. To put an easy example, your code might need to read data stored at some location on your machine where the JVM is active. You might realize later that the location of the file has either been changed or the file you are trying to access has been renamed or corrupt. These are some common issues while dealing with external resources. Java has been designed in such a manner that it let you understand the fact that the expected operation might end up with an error scenario for which you might not be aware of. So better to handle such exception so that in case such scenario appears, you at least know what went wrong and corrective measure could be taken accordingly. Example for such exception could be – FileNotFoundExcpetion, InterruptedIOException, MalformedURLException, UnknownHostException etc. All these exceptions are derived from java.lang.IOException class.

The two types of exceptions we talked above are derived from java.lang.Exception class. If you are creating your own checked exception then either your exception class can extend java.lang.Exception or if you are sure about its type then your class can extend specific one. But if you are creating your own unchecked exception then your class must extend java.lang.RuntimeException class or any sub-class of it, if you are sure about the type. This is because java.lang.Exception is of type checked exception itself.

On top of the exception class there sits java.lang.Throwable class. This class pretty much able to take care of exceptions as well as programmatic errors. It can not definitely handle an error scenario where your machine is switched-off. So let us see what is an error in java.

Error : As per Oracle specification – “Error indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.” The important fact to note about is – ‘a reasonable application should not try to catch’. Example for error could be – IOError, ThreadDeath etc.

Difference Between Throws and Throw

  • We use ‘throws’ in method declarations where the contents of the method may throw an exception. In this way the responsibility to handle the exception is passed to the caller of the method.

  • whereas ‘throw’ keyword can be used in method bodies to explicitly throw an exception.

Creating Your Own Exception

Java gives you the facility to create your own exception. To create a checked exception, you could subclass ‘Exception’ class or any of its subclass except RuntimeException and its child :

Class MyOwnException extends Exception {

}

You can create your own runtime exception by extending RuntimeException class.
Class MyOwnException extends RuntimeException {

}

COMMON EXCEPTIONS

1) NullPointerException – is JVM thrown exception.
Example: String s = null;
.
.
System.out.println(s.length());

When you attempt to access an object using a reference variable with the current value of null.

2) ArrayIndexOutOfBoundException – is a JVM thrown exception. This occurs while attempting to access an array with an invalid index value.

3) IllegalStateException – is a responsibility of a developer. It is thrown when the state of the environment doe snot match the operation. Example : Using a scanner that has been closed.

Few more commonly known exceptions and could generally be introduced by :
– ClassCastException – By JVM
– NumberFormatException – By Developer
– IllegalArgumentException – By Developer
– AssertionError – By Developer
– NoClassDefFoundError – By JVM

Previous articleJSP Directives
Next articleCollection API
I have spent almost 10 years playing around Java and related technologies. I love to write on different topics and would be very much willing to hear back your feedback/suggestions on them. This site is a medium to share my knowledge with the Java folks and grow further. My other interests include traveling, driving, swimming and dance. But yes, my web site has become my passion over the time :) I live in Scotland and travel to India often, my roots being there.

NO COMMENTS

LEAVE A REPLY