Over

120,000

Worldwide

Saturday - Sunday CLOSED

Mon - Fri 8.00 - 18.00

Call us

 

Java Exception Handling

Java Exception Handling

Checked and Unchecked Exceptions

In Java when a problem arises during the execution of a program, is called Exception. The handling of exceptions in Java enables developers to manage the various types of errors and exceptions, that occur in the runtime execution. The exceptions are unwanted errors or bugs that bother the project’s execution.

There can be different reasons for the occurrences of exceptions:

1. when provided an invalid data by user,

2. file that is requested, doesn’t exist,

3. when the JVM runs out of its memory,

4. network drops and so on.

So, let’s firstly see the hierarchy of the Exceptions and Errors.

So, as you see the head class of them all as we know is Object, then for the Error and Exception we have the Throwable superclass. Only the objects which are instances of this class, are thrown by the Java Virtual Machine or can be thrown by the Java throw statement.

The Error class is used by Java runtime system, for such errors that have to do with the runtime environment. An example of this can be the StackOverFlowError or OutOfMemoryError.

The Exception class is used for exceptional conditions, like having a NullPointerException or IndexOutOfBoundsException.

This is a powerful mechanism to handle runtime errors, with the advantage of maintaining the normal flow of the application.

There are two types of RuntimeExceptions:

1. Checked exception, which is the exception validated in the compile time, 2. Unchecked exception, which is the exception handled in the runtime of the application. The checked exceptions, as already said, are compile-time exceptions and they are checked during the compilation of the application, to see if the exception is handled or not. If it is not checked then it will result in compilation error, like IOException, ClassNotFoundException and so on.

For a better understanding, let’s look at this simple example:

import java.io.FileInputStream;

public class CheckedExcExample1 {

public static void main(String args[]) {

FileInputStream fileInputStream = new FileInputStream(“D:/newFile.txt”); int index;

while ((index = fileInputStream.read()) != –1) {

System.out.print((char) index);

}

fileInputStream.close();

}

}

Here on the FileInputStream initialization line, we have our compile error which tells, “Unhandled exception: java.io.FileNotFoundException”. In the reading of the file, we also have a checked exception, cause the file is not found, and the same about closing the file input stream.

For reaching to a solution for this, we have few ways:

Throws keyword

With the usage of throws keyword, we will have this code:

import java.io.FileInputStream;

import java.io.FileNotFoundException;

public class CheckedExcExample1 {

public static void main(String args[]) throws FileNotFoundException {

FileInputStream fileInputStream = new FileInputStream(“D:/newFile.txt”); int index;

while ((index = fileInputStream.read()) != –1) {

System.out.print((char) index);

}

fileInputStream.close();

}

}

When we throw this method to FileNotFoundException, we will get rid of the compile error on the initialization line, but on reading it and closing, you can still see the compile error. For this we should throw the method to IOException, too. But, because the FileNotFoundException extends IOException, then there is no need to throw to both of them, only the IOException is enough. So, the code will have this look:

import java.io.FileInputStream;

import java.io.IOException;

public class CheckedExcExample1 {

public static void main(String args[]) throws IOException {

FileInputStream fileInputStream = new FileInputStream(“D:/newFile.txt”); int index;

while ((index = fileInputStream.read()) != –1) {

System.out.print((char) index);

}

fileInputStream.close();

}

}

And this doesn’t have a compile error now.

So, the throws keyword is used for declaring the exceptions that can occur during the execution of the program. For any method that may throw exception, this is a mandatory use.

Another way to resolve exceptions you can do with try-catch blocks.

Here we resolve the same code, using try-catch blocks:

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

public class CheckedExcExample1 {

public static void main(String args[]) {

FileInputStream fileInputStream = null;

try {

fileInputStream = new FileInputStream(“D:/newFile.txt”);

} catch (FileNotFoundException e) {

System.out.println(“The file does not exist with this path!” + e);

}

int index;

try {

if (fileInputStream != null) {

while ((index = fileInputStream.read()) != –1) {

System.out.print((char) index);

}

fileInputStream.close();

}

} catch (IOException e) {

System.out.println(“IOException found! : ” + e);

}

}

}

So, when the compiler tries to get a file with the specified path and doesn’t find it, then it will warn us about the exception that is handled. Otherwise, it will successfully read the file. This is a classical approach to handling Java exceptions:

1. firstly, we have the try block that has the code in it, which might throw an exception, 2. then we can have one or several catch blocks to handle the caught exceptions, 3. and we can have a finally block, which is being executed after the try block is executed successfully or after an exception is thrown, meaning always it will execute.

The try block is required, we should use it either with catch block or finally block, or both of them, but one of them should be, that is mandatory.

The finally block, as already mentioned, executes ALWAYS, whatever happens in try catch blocks, doesn’t matter when the try block has a return statement or even when catch block returns a RuntimeException. The purpose of having this block is to have the cleanup logic there, like closing a connection or an InputStream.

The unchecked exceptions are those, which occur during the execution of the program, meaning in the runtime of the application. Hence, they are also called Runtime Exceptions. These exceptions we cannot get during the compilation process. For example, bugs like logical errors or using wrong APIs.

Let us consider the following code:

public class RuntimeExcExample1 {

public static void main(String[] args) {

int[] numbers = {1, 2, 5, 6, 8};

try {

String newString = null;

System.out.println(numbers[6]);

System.out.println(newString.charAt(1));

} catch (ArrayIndexOutOfBoundsException e) {

System.out.println(“ArrayIndexOutOfBoundsException caught!\n+ e); } catch (NullPointerException e) {

System.out.println(“NullPointerException caught!\n+ e);

}

}

}

Here as we see, the string is initialized to null and we try to get a char from it, this will result in NullPointerException. But before it we also have a numbers array and try to print the sixth indexed element from it. This will result with ArrayIndexOutOfBoundsException, and the output will be:

ArrayIndexOutOfBoundsException caught!

java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 5

Another example that we will get during the runtime, can be this:

public class RuntimeExcExample2 {

public static void main(String[] args) {

try {

int[] array = new int[6];

array[8] = 2;

} catch (ArrayIndexOutOfBoundsException e) {

System.out.println(“The array index is out of bound!\n+ e);

}

}

}

Here we have an array that has a size of 6, then we are providing a value that is beyond the length of the array.

This will result with:

The array index is out of bound!

java.lang.ArrayIndexOutOfBoundsException: Index 8 out of bounds for length 6

The user can create his own exceptions in Java. It should follow few points: 1. All exceptions must be child of Throwable,

2. For writing a checked exception it must be extended from the Exception class. 3. For writing a runtime exception, it is needed to extend the RuntimeException class. We can define our own exception like this:

public class UserDefinedExcExample1 extends Exception {

private double amount;

public UserDefinedExcExample1(double amount) {

this.amount = amount;

}

public double getAmount() {

return amount;

}

}

Here we have this class extended from Exception.

And so, we can define the exceptions extending from the Exception or Runtime Exception classes.

Let’s view another extended example using try/catch and finally blocks:

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

public class ExceptionExample {

public static void main(String[] args) {

BufferedReader bufferedReader = null;

try {

String currentLine;

bufferedReader = new BufferedReader(new FileReader(“file1.txt”));

while ((currentLine = bufferedReader.readLine()) != null) {

System.out.println(currentLine);

}

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

if (bufferedReader != null)

bufferedReader.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

This is a common code example, used in applications which demand many IO operations. The result for this will be the content of the file:

This is an example to read from file

The code in try and catch blocks has some logic. The finally block here is used for saving the resources, for closing the file in it.

Anyway, from Java 7, there is another way of solution to this. We can have the file opened inside the try brackets. Like in this example:

try (BufferedReader reader = new BufferedReader(new FileReader(“file1.txt”))) { String currentLine;

while ((currentLine = reader.readLine()) != null) {

System.out.println(currentLine);

}

} catch (IOException e) {

e.printStackTrace();

}

By writing in such syntax, we will again have the same result in the output.

In Java, we have two categories of Exceptions and Errors:

1. JVM Exceptions, that are those ones that are exclusively or logically thrown by the JVM, like NullPointerException, ArrayIndexOutOfBoundsException and so on.

2. Programmatic Exceptions, these are the ones that are thrown by the application or the API developers, like IllegalStateException or IllegalArgumentException.

So, java offers two types of exceptions, checked and unchecked. We use the checked exceptions whenever they are expected and handled in the compilation time. It can be handled with a try-catch finally blocks and handling within a method. If we specify it in the method, it becomes part of the method declaration. We use unchecked exceptions for runtime errors, but we do it in the same way that we handle or specify a checked exception.

Previous

Next

Leave a Reply

Your email address will not be published. Required fields are marked *

Working Hours

  • Monday 9am - 6pm
  • Tuesday 9am - 6pm
  • Wednesday 9am - 6pm
  • Thursday 9am - 6pm
  • Friday 9am - 6pm
  • Saturday Closed
  • Sunday Closed