Exception Handling Using Try-Catch in Java Programming

By  Shaurya Singh    216 - 02 September, 20
exception-handling-using-try-catch-in-java-programming

Share article on social media


Exception handling in Java programming is one of the most powerful mechanism to handle runtime errors, so that, the normal flow of the program can be maintained.

TYPES OF EXCEPTIONS:

1) Checked Exceptions - All exceptions other than run time exceptions are known as checked exceptions as the compiler will check whether the programmer has handled them during compilation or not. If the exceptions are not handled then it will give a compilation error. Ex - ClassNotFoundException, EOFException, IllegalAccessException, etc.

2) Unchecked Exceptions - Runtime exceptions are known as unchecked exceptions as the compiler does not check whether they have been handled by the programmer or not. However, it is duty of the programmer to handle these exceptions in order to provide a fully functional code.

Examples - ArrayIndexOutOfBoundsException, ArithmeticException, NullPointerException, etc.

WHEN CAN AN EXCEPTION OCCUR?

An exception can occur at both run time and compile time.

DIFFERENCE BETWEEN ERRORS AND EXCEPTIONS:

1) Errors - Indicates serious problems and abnormal conditions that most applications should not try to handle. Errors define problems that are not expected to be caught under normal circumstances. Ex - Memory error, Hardware error, JVM error, etc.

2) Exception - These are conditions within a code. A developer can handle these conditions and take necessary corrective actions. Ex - DivideByZeroExceptinon, NullPointerException, etc.

In Java Exceptions are handled using a TRY & CATCH Blocks. Below we'll see in detail how these blocks are used.

JAVA TRY BLOCK:

Java try block is used to enclose the doubtful code that might throw an exception. It must be used within a method. The java try block is immediately followed by either a catch block or by a 'finally' block or by both.

The syntax of java Try-Catch:

try{
//code that may throw an exception

}catch(Exception_class_Name ref){}

The syntax of java Try-Finally:

try{

//code that may throw an exception

}finally{}

JAVA CATCH BLOCK:

The code written to handle the exception is written inside the Java catch block. The Catch block if must be written after the try block only. Java also allows us to use multiple 'catch' blocks for a single try block as well.

try{

//code that may throw an exception

}catch(Exception e){

System.out.println(e); //will print out the message produced by the program.

}

JAVA MULTI-CATCH BLOCK:

A try block can be followed by a single or multiple catch blocks. If we use multiple catch blocks then each catch block must contain a different exception handler. If you need to perform different tasks at the occurrence of different exceptions use multi catch block. Note: At a time only one exception can occur and at a time only one catch block can be executed. In Order to catch a particular exception all 'catch' blocks must be ordered from most specific to least specific, i.e. the child classes should come before the main parent class. For ex. exception for ArithmeticException must come before Exception.

Example of multi catch block program :-

class Example{

public static void main(String args[]){

try{ int arr[]=new int[7];

arr[4]=30/0;

System.out.println("Last Statement of try block");

} catch(ArithmeticException e){ System.out.println("You forgot to read basic mathematics in school."); } catch(ArrayIndexOutOfBoundsException e){ System.out.println("Accessing array elements outside the limit"); }

catch(Exception e){ System.out.println("Some Other Exception"); }

System.out.println("Out of the try-catch block"); }

}

Output: java.lang.ArithmeticException:You forgot to read basic mathematics in school.

Out of the try-catch block

From the above program, we can clearly understand that when an exception occurs then the specific catch block handling the exception is executed and as soon as an exception is encountered rest of the try block is not run. Further, in the above code if the exception is neither an ArithmeticException or an ArrayIndexOutOfBoundsException the generic Exception catch block is executed. After displaying the exception message the program resumes normal flow outside the try block.

JAVA NESTED TRY BLOCK:
Sometimes a situation a block of code may result in an exception and the entire block itself may cause another exception. In order to overcome this problem exception handlers need to be nested. This can be achieved by using nested try block.

General syntax of nested try block :-

try{

statement 1

statement 2

try{

statement 1

statement 2

}catch(Exception e){}

}catch(Exception e){}

Thanks for reading this article, read more articles about programming on NoobtoDev.