Exception handling in java

This post describes what are exception and how to properly handle them.

5/10/20232 min read

What are Exceptions

Exception is an event which halts the normal execution of the program .Java provides features to catch and handle the exception .

Components of Exception handling

1)Try block:-The code where exception can occur is enclosed within the try block.When an exception occurs an object of that exception class is created and thrown.

2)Catch block :-The exception thrown is caught by catch block .All catch blocks are designed to catch a particular type of exception .

3)Finally block:-This block is always executed whether any exception is raised or not Activities like closing files,ending the database connection .If an exception is raised and not caught by catch block causing abnormal termination of program execution ,even then finally block is executed .

public class ExceptionDemo

{

try

{

int[] arrayTemp={30,32,34,0,30};

for(int i=0;i<arrayTemp.length;i+=)

{

i=500/arrayTemp[i];

System.out.println(i);

}

catch(ArithmeticException e)

{

System.out.println("Divide by zero exception ");

}

}

Output

Divide by zero exception

Program explanation

The above program iterates over integer array and divides 500 by every element of the array,since one of the element is zero,it will throw an exception ,which will be caught by the catch block .

Hierarchy of Exception class.

The base class for all exception classes is Throwable class. Throwable class has two branches Exception and Error .Exception class represents those unexpected events occurring during the execution of the program which should be caught and handled.Errors are raised by the environmental ,for example JRE may raise error due to lack of system resources.

Types of exception

1)Built-in Exception

These exceptions are already defined in the programming language ,for example nullpointerexception.They are of two types .

a)Checked Exception:-The code is scanned for these exceptions at compile time.The compiler expects that these exceptions should be handled ,or the method should declare that it throws this exception using throws keyword ,otherwise compile time error happens,eg SQLException, IOException, ClassNotFoundException,InterruptedException.

b)Unchecked Exception :-The program execution cannot recover if these exceptions occur .These exceptions don't need to be handled,e.g. ClassCastException,ArrayIndexOutOfBounsException.

2)User Defined Exception :-Exceptions created based on specific use case are called user defined exception.