Exception Handling in Java

In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.

The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that normal flow of the application cannot be terminated.

An exception can occur for many different reasons. Following are some scenarios where an exception occurs.

A user has entered an invalid data.
A file that needs to be opened cannot be found.
A network connection has been lost in the middle of communications or the JVM has run out of memory.

Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner.

Advantage of Exception Handling

An exception normally disrupts the normal flow of the application that is why we use exception handling. Let’s take a scenario:

  • statement 1;
  • statement 2;
  • statement 3; //exception occurs
  • statement 4;
  • statement 5;
  • statement 6;
  • statement 7;
  • statement 8;
  • statement 9;
  • statement 10;

Assume that, there are 10 lines in our program, and the exception came at the 3rd line of our program, if we have not handle the exception, then the program abnormally terminated and from the line 4 to line 10 will not be executed.

If we handle the exception, the JVM will take care of exception and the remaining lines will be executed completely.

Hierarchy of Java Exception classes

The java.lang.Throwable class is the root class of Java Exception hierarchy which is inherited by two subclasses: Exception and Error.

// Java program to demonstrate how exception is thrown.

class ThrowsExecp{
public static void main(String args[]){
String str = null;
System.out.println(str.length());
}
}

Exception in thread “main” java.lang.NullPointerException

at ThrowsExecp.main(File.java:8)

Types of Java Exceptions
Checked Exception
Unchecked Exception

Checked exceptions

All exceptions other than Runtime Exceptions are known as Checked exceptions as the compiler checks them during compilation to see whether the programmer has handled them or not. If these exceptions are not handled/declared in the program, you will get compilation error. For example, SQLException, IOException, ClassNotFoundException etc.

Unchecked Exceptions

Runtime Exceptions are also known as Unchecked Exceptions. These exceptions are not checked at compile-time so compiler does not check whether the programmer has handled them or not but it’s the responsibility of the programmer to handle these exceptions and provide a safe exit. For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.

Compiler will never force you to catch such exception or force you to declare it in the method using throws keyword.

Java try and catch

We can handle exception either try catch or throws keyword.

See the example bellow.

This will generate an error, because myNumbers[10] does not exist.

public class MyClass {
public static void main(String[ ] args) {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]); // error!
}
}

The output will be something like this:

Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 10
at MyClass.main(MyClass.java:4)

For the above error we need to handle exception like mentioned bellow.

public class MyClass {
public static void main(String[ ] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println(“Something went wrong.”);
}
}
}

The output will be:
Something went wrong.

Finally

The finally statement lets you execute code, after try…catch, regardless of the result:

public class MyClass {
public static void main(String[] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println(“Something went wrong.”);
} finally {
System.out.println(“The ‘try catch’ is finished.”);
}
}
}

The throw keyword

The throw statement allows you to create a custom error.

The throw statement is used together with an exception type. There are many exception types available in Java: ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, etc:

Example:

Throw an exception if age is below 18 (print “Access denied”). If age is 18 or older, print “Access granted”:

public class MyClass {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException(“Access denied – You must be at least 18 years old.”);
}
else {
System.out.println(“Access granted – You are old enough!”);
}
}
public static void main(String[] args) {
checkAge(15); // Set age to 15 (which is below 18…)
}
}

The Output will be

Exception in thread “main” java.lang.ArithmeticException: Access denied – You must be at least 18 years old.at MyClass.checkAge (MyClass.java:4)at MyClass.main(MyClass.java:12)

The Output will be

If age was 20, you would not get an exception:

checkAge(20);

The Output will be

Access granted – You are old enough!

Throws

Throws is a keyword in Java which is used in the signature of method to indicate that this method might throw one of the listed type exceptions. The caller to these methods has to handle the exception using a try-catch block.

class tst
{
public static void main(String[] args) throws InterruptedException
{
Thread.sleep(10000);
System.out.println(“Hello TCDC”);
}
}

In the above program, by using throws keyword we handled the InterruptedException and we will get the output as Hello TCDC

Another Example:

// Java program to demonstrate working of throws

class ThrowsExecp
{
static void fun() throws IllegalAccessException
{
System.out.println(“Inside fun(). “);
throw new IllegalAccessException(“demo”);
}
public static void main(String args[])
{
try
{
fun();
}
catch(IllegalAccessException e)
{
System.out.println(“caught in main.”);
}
}
}

throws keyword is required only for checked exception.

By the help of throws keyword we can provide information to the caller of the method about the exception.

Spread the love