Exception Handling

While writing a program, it is obvious that any abnormal condition may arise.By abnormal condition we mean, a condition that effects the normal execution of our code. When these conditions occur, the execution of our code is likely to stop. Generally, we refer this abnormal condition as an error. But to say it error every-time, is not correct. If our code is able to handle this weird condition, then we’ve to say it an exceptional condition or simply an exception. And the process to handle this exception is known as exceptional handling.

Consider a scenario in which you have to call a method, about which you are not sure that whether it is going to work properly or not. But since you have to include this code fragment you also cannot ignore it. In these kind of situations, you need to apply exception handling mechanism, which will handle this delicate method so that rest of your code is executed normally. Exception handling is considered as a crucial part of java’s body since it handles the exceptions that occur during run-time.

Exception Types:- All types of exceptions come under one big class known as Throwable. Under this Throwable class, there are two sub-classes, which are:-
1) Exception:- This sub-class includes those exceptions that should be caught by our program. Some of its sub-classes are ClassNotFoundException, IOException, RuntimeException (most important), etc. Under RuntimeException, there are few more sub-classes which are ArithmeticException, NullPointerexception, ArrayIndexOutOfBoundException, etc.
2) Error: The second sub-class of Throwable; which defines those exceptions that our program is unable to catch. For example, Out of Memory Error, Virtual Machine Error, Thread Death Error.

Checked and Unchecked exceptions: All code written in java run within java’s environment called java run-time environment. Thus, the exceptions that occur out of this environment are referred as checked exceptions, while those that lie within this environment, are known as unchecked ones.

Checked exceptions generally occur due to programmer’s mistake. Thus, for a programmer it is advisable to always apply an exception handler while working with checked exceptions so that a running program does not stop on client side. The exceptions like; Class Not Found, SQL, IO, etc. come under checked exceptions. Unchecked exceptions includes those exceptions that come under Error (Sub-class of Throwable) and RuntimeExceptions (Sub-class of Exception). 

Try and Catch:-
Even-though java has provided default exception handlers, but still we may want to handle exceptions by our own. Applying our own exception handler, we prevent our code from automatic termination as well as we can check for the errors and fix them. For this java gave us two keywords namely try and catch. If we have any risky code, we simply enclose this in the try clause, and if any exception occurs in this code, we can handle this in the catch clause.You can use any number of try and catch clauses in your code.

Note: The catch clause comes immediately after the try clause. No other method, variable or any code can be declared between these two clauses. 

A sample code for exception handling;

class DivideByZeroException
{
int denominator1=10, denominator2=0, numerator=20;
void noException()
{
int result= numerator/denominator1;
System.out.println(result);
}
void willThrowException()
{
int result=numerator/denominator2;
System.out.println(result);
}
public static void main(String a[])
{
DivideByZeroException obj=new DivideByZeroException();
obj.noException();
try{
obj.willThrowException();
}
catch(ArithmeticException e)
{
System.out.println(“Division by 0”);
}
System.out.println(“After try/catch”);
}
}

Output: 2
Division by 0
After try/catch.

Nested try:- Nested try simply means try within a try. If there is risk in any code, then you can surely place it inside try block. And inside this try block, you can even take some more risks by placing few more try blocks. But remember, every try block is to be paired with a catch block. The structure of nested try looks like:
class NestedTry
{
try
{
try
{
// some code
}
catch(Exception e) // catch of nested try
{
//some code
}
}
catch(Exception e) //catch of first try block
{
//some code
}
}
In the above discussion we saw that it is possible to have nested try blocks in which we can apply as many number of try/catch blocks within a try block. Now you must be having a question in your mind, that can we use try/catch block inside catch block? Well the answer for this is yes, you can do so. But having a try/catch block inside a catch is not considered as a good programming pattern. By doing so the complexity of your code increases. Also by throwing one exceptions your code becomes slower and placing another handler inside the catch makes it more slower.

try with multiple catches:- Apart from nested try, one can apply as many numbers of catches with a single try. In situations where your code is likely to throw more than one exception, or if you are not sure which exception will be thrown, it is advisable to apply more than one catch with that code. When an exception is thrown, each catch block is inspected (starting from first), and the block whose type matches is executed. After one is executed the others are bypassed. Structure for multiple catches with a single try looks somewhat like:
class MultipleCatches
{
try
{
//some risk
}
catch(ArithmeticException e)
{
//1st catch block
}
catch(ArrayIndexOutOfBoundException e)
{
//2nd catch block
}
catch(NullPointerException e)
{
//3rd catch block
}
}
Remember that the exception types which are super-classes of some other exceptions cannot be used first while working with multiple catches. As explained before, in the exception class hierarchy, Exception and Error are the two classes which come at the top of every other exception class. Thus, in multiple catches if we define any super class before any-other sub-class then the compiler will give us a code unreachable error. For example, if in the above code structure, we’ve written catch(Exception e) as the first catch statement and catch(ArithmeticException e) as the second catch statement, then our code will definitely give the error. But still, we can do the vice-versa, i.e. we can write any sub-class exception before a super-class exception. In other words we have to use child class exceptions before its parent class.

throw, throws:-

The throw keyword is used to throw an exception explicitly. We use this keyword to throw our own exceptions. However, these must be an object of type Throwable. General form of throw is; “throw ThrowableInstance;”. There are two ways to obtain a Throwable object, first is by using a parameter in the catch clause, second by creating one with the new operator. As soon as a throw statement is encountered, the flow of execution stops and the control is transferred to the try clause, if and only if it has a catch that matches the type of exception which is generated. If no such try and catch are found, the default exception handler halts the program and prints the stack trace.

While the throws keyword is used in case where a method is likely to cause an exception and is unable to handle it. In these cases, the method have to specify this behavior by including throws clause in its declaration so that the caller can guard itself against the exception.

The “finally” block:- Apart from the try and catch clauses, there is another important clause known as finally. Sometimes it becomes necessary to execute a method. But before that method, you have a risky code which may in-turn risk the execution of your unavoidable method. For the situations like this, java gave us finally block. In a finally block, you may put a code that must run regardless of an exception. There are few rules which must be followed while using a finally block, and these are:
1) It is always executed, no matter if there is an exception or not.
2) The finally block cannot be used alone, i.e, it is to be paired with a try catch block and must always be placed after the catch clause (not before catch).
3) More than one finally block can never be used with a single try clause.

A finally block is executed after a try/catch block has completed and before the code following the try catch block. Following is a simple example for finally block;

class ExampleForFinally
{
int show()
{
try
{
return 10;
}
finally
{
return 20;
}
}
public static void main(String a[])
{
int x= new Hi().show();
System.out.println(x);
}
}
Output: 20.

With a try block, it is necessary to use either catch or finally block. No try block can be ever be used alone in any piece of code. This is because inside a try block we put our risky code, and if we do not put any handler for this risky code then what do you think will be the use of exceptional handling mechanism. Thus, every-time you take any risk it is your responsibility to handle it so that your code do not terminate immaturely.

Try out the Exception Handling codes in Whizlabs OCPJP 6 Training Course

About Aditi Malhotra

Aditi Malhotra is the Content Marketing Manager at Whizlabs. Having a Master in Journalism and Mass Communication, she helps businesses stop playing around with Content Marketing and start seeing tangible ROI. A writer by day and a reader by night, she is a fine blend of both reality and fantasy. Apart from her professional commitments, she is also endearing to publish a book authored by her very soon.
Scroll to Top