Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Java Exception Handling Overview

In this article we will have an overview about the Exception Handling in Java. We will see what is this and how to work with it.

Let us start our introduction to exception handling in Java by compiling the following piece of code and see the result:

Listing 1: A code sample containing exception

import java.io.*;

class BasicExample{
	public static void main(String[] args){
		File file  = new  File("examplefile.txt");
		FileReader file_reader = new  FileReader(file);
	}	
};

Executing the code in listing 1 gives us the following output:

output of listing 1

Figure 1: output of listing 1

The result shows that there is a mistake in our code, and describes it as unreported exception, which must be caught or declared to be thrown. You must have faced such type of error while programming. This type of error is called Exception in Java and is part of its error handling method.

“Exception” in Java stands for the phrase “exceptional event”, which occurs during the execution of a program, altering the normal flow of program’s instructions. When an exception occurs at a line in the code, the Java runtime system stops execution of the next instruction in the flow, and starts searching for the code written to handle the exception. If a handler for the exception generated exists, its code is executed, else the program terminates.

This article will try to cover the following areas:

  • Different classes of exception and their hierarchy
  • Handling the exceptions using try-catch-finally
  • Exceptions thrown by methods
  • Chained Exceptions
  • Advantages and disadvantages of Exceptions

Types of Exceptions

A valid code in Java must fulfill the Catch or Specify Requirement to handle exceptions. This requirement states that a piece of code that might throw certain exceptions must be enclosed within either of the following:

  • A try statement that catches the exception. Also the try statement should provide a handler for the exception.
  • A method specifying that it can throw the exception. The method should provide a throws clause stating all the exceptions that the code can throw.

Any code that does not fulfill the above requirement will not compile.

Let us try to compile and execute another piece of code.

Listing 2: A code violating the Catch or Specify requirement

import java.io.*;
import java.net.*;

class ExceptionCategoriesExample{
	public static void main(String[] args){
		String address = "http://www.example.com";
		URL url = new  URL(address); // (1)
		int[] primeNumbers = new  int[3];
		primeNumbers = new  int[] {2,3,5};
		System.out.println("Prime number at 4th position in primeNumbers : " + primeNumbers[3]);
		System.out.println("This is a logical error : " + 2/0);
	}
};

Result of compilation of code in listing 2 is as follows:

Result of listing 2

Figure 2: Result of listing 2

Exceptions can be categorized into the following three types:

  • Checked Exceptions
  • Runtime / Unchecked Exceptions
  • Errors

Checked Exceptions: Exception reported in listing 2 is an example of checked exceptions. We have tried to create an object of URL class by providing a String address in its constructor at (1). It can throw an exception if the String address can’t be correctly parsed to URL syntax. An application should anticipate and recover from such type of exceptions. They are subject to Catch or Specify Requirement i.e. the code should either be enclosed in try block or should declare the exception in the throws statement. All exceptions that are not indicated by Error, RuntimeException or their subclasses are checked exceptions, for e.g. MalformedURLException, FileNotFoundException.

Let us modify our code a little bit to take care of the checked exception by adding throws statement to the declaration of main function.

Listing 3: An example of runtime/unchecked exception

import java.io.*;
import java.net.*;

class ExceptionCategoriesExample{
	public static void main(String[] args) throws MalformedURLException{
		String address = "http://www.example.com";
		URL url = new URL(address); //Checked Exception
		int[] primeNumbers = new int[3];
		primeNumbers = new int[] {2,3,5};
		System.out.println("Prime number at 4th position in primeNumbers : " + primeNumbers[3]);
		System.out.println("This is a logical error : " + 2/0);
	}
};

On compiling and executing the code in listing 3, JVM returns the following result.

Result of listing 3

Figure 3: Result of listing 3

Runtime Exceptions / Unchecked Exceptions: The result shows that code was compiled successfully. The exception occurred during execution/runtime of the code. Reported exception is java.lang.ArrayIndexOutOfBoundsException which occurs when we provide index of the array as negative or greater than (arraySize -1) to access an element.Here we tried to access the array by giving index 3 which is greater than (arraySize -1) i.e. (3 - 1).Exceptions like these are internal to the application, but usually it is difficult to anticipate them or recover from them. Their cause can be improper use of API or incorrect programming logic. RuntimeException and its subclasses are used to represent such type of exceptions.

Errors:Third category of exceptions is Error and the application can’t usually anticipate or recover from these. They are external to the application. Java indicates these by Error and its subclasses. Examples of errors are Out of memory error.

Exception handling using try-catch-finally

Java follows the throw-and-catch paradigm for exception handling. Any code that reports an exception is said to have thrown the exception. The exception thrown is handled by the exception handler written either in the same context, or any level above the context in the execution stack.

try-catch-finally construct in Java consists of three blocks namely - try, catch and finally. Its syntax is as follows :

try{
	//exception throwing block
}catch(type of exception handled){
	//exception handling code
}finally{
	//code to be executed after exception is handled
}

try block

The first step in exception handling is to enclose the code that can throw an exception inside the try block. The try block can enclose either a single valid Java statement or multiple valid Java statements.

catch block

Next in the series of steps for exception handling is the catch block. It follows immediately after the tryblock and no code can exist between the tryand catchblocks. catchblock works as the handler of the exception that is suspected to be thrown in the tryblock. The exception handled by the catch block is specified in the arguments of the catchstatement.As seen before in listing 2,the compiler reported an exception. This was raised because the code did not follow the catch or specify requirement. We added throws statement to the main function declaration. Another way to handle that is by enclosing the code in try- catchblock. Let us modify the code to see how it is done.

Listing 4: Example of try-catch block taking care of checked exception only


import java.io.*;
import java.net.*;

class ExceptionHandlingTryCatch{
	public static void main(String[] args){
		try{
		String address = "htt";
		URL url = new URL(address); //(1) Checked Exception
		int[] primeNumbers = new int[3];
		primeNumbers = new int[] {2,3,5};
		System.out.println("Prime number at 4th position in primeNumbers : " + primeNumbers[3]); //(2) Unchecked Exception
		//System.out.println("This is a logical error : " + 2/0);
		}catch(MalformedURLException e){
			System.out.println("URL is malformed");
		}
	}
};

In listing 4 the lines causing exception at (1) and (2) have been enclosed inside a try block. We could have enclosed only the line at (1) inside a try block and the code would have worked, since it is the only checked exception which is found at compile time. The compiler doesn’t force us to enclose the line at (2) inside a try block since it is an unchecked/runtime exception. We get the following result when we compile and execute the code in listing 4.

Result of listing 4.

Figure 4: Result of listing 4.

As we can see in the result, the compilation was successful. This implies that the code fulfilled the Catch or Specify requirement by enclosing the code suspected to throw exception inside a try block. In the execution result we can see that the output is “URL is malformed”. This gives us an idea about the flow of execution of code. In the example the string passed in URL constructor is an incorrect URL syntax. As soon as the exception is encountered at (1)inside the try block, the flow skips all the code after it, and reaches the exception handler defined in the catch block. As evident from the declaration of the catch block catch(MalformedURLException e), it explicitly handles the declared type of exception and its subclasses. On reaching the exception handler the code inside it gets executed and the JVM exits. Hence the result “URL is malformed”.

Let us modify the code a little more as shown below:

Listing 5: A code sample catching unchecked exception also

import java.io.*;
import java.net.*;

class ExceptionHandlingTryCatch{
	public static void main(String[] args){
		try{
		String address = "http://www.example.abc";
		URL url = new URL(address); //(1) Checked Exception
		System.out.println("URL constructor did not raise exception. Going further.");
		int[] primeNumbers = new int[3];
		primeNumbers = new int[] {2,3,5};
		System.out.println("Prime number at 4th position in primeNumbers : " + primeNumbers[3]); //(2) Unchecked Exception 
		System.out.println("If unchecked exception is raised this will not get printed"); // (3)
		//System.out.println("This is a logical error : " + 2/0);
		}catch(MalformedURLException e){
			System.out.println("URL is malformed");
		}
		catch(ArrayIndexOutOfBoundsException e){
			System.out.println("Array index is out of bounds");
		}
	}
};

The compilation and execution of code in listing 5 results in the following output:

Result of listing 5.

Figure 5: Result of listing 5

As it is evident from the output that the code at (1) did not throw any exception since the println statement is executed after that. As we know that the code at (2) throws a runtime exception a catch block is added to handle the ArrayOutOfBoundsException. It is not mandatory to catch a runtime exception. The result also shows that when the code at (2) raised an exception, all the statements after it were skipped and the execution reached the catch block, printing the arguments of the println statement. We can do much more useful things in the catch block, other than printing a simple statement.

finally block

The finally block is executed always after the exit from try block, thus ensuring that its execution occurs even in case of an unexpected exception. Other than exception handling, any cleanup code can also be placed inside the finally block, thereby avoiding the accidental bypassing of any cleanup code by return, break or continue. In fact, it is a good practice to put the cleanup code inside finally even when no exception is anticipated, which avoids code duplicity.

Listing 6: Sample code with try-catch-finally

import java.io.*;
import java.net.*;

class ExceptionHandlingTryCatchFinally{
	public static void main(String[] args){
		try{
		String address = "htt";
		URL url = new URL(address); //(1) Checked Exception
		System.out.println("Clean up code written after this may be bypassed!!!");
		}catch(MalformedURLException e){
			System.out.println("Caught an exception !!!!!!!!!! URL is malformed");
		}catch(ArrayIndexOutOfBoundsException e){
			System.out.println("Array index is out of bounds");
		}finally{
			System.out.println("Clean up code in try bypassed. Use this block to do any cleanup after try catch!!!!!");
		}
	}
};

The result of executing code in listing 6 is as follows:

Result of listing6

Figure 6: Result of listing 6

As the result shows an exception raised at (1) is caught in a catch block and after that code inside finally block is executed. It is useful to put cleanup code in finally block, when occurrence of an exception bypasses the rest of the cleanup code, as shown in listing 6.

try-with-resources statement

Introduced in the Java SE7, the try-with-resources statement is a try statement with declaration of one or more resources. A resource can be any object that must be closed after the completion of its use by the program. Example of resource can be an inputstream, filewriter, connection object to name a few. try-with-resources ensures the resources declared in the try statement are closed at the end of the try statement. Any object that implements java.lang.AutoCloseable or java.io.Closeable can be used as a resource.

Listing 7: Sample code showing the implementation of try-with-resources statement


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class TryWithResources {
	
	public static void main(String[] args) {
		try{
			String filePath = "C:\\sample.txt";
			System.out.println(readFirstLineFromFile(filePath));
		}catch(IOException e){
			System.out.println(e.getCause().toString());
		}
	}
	
	static String readFirstLineFromFile(String path) throws IOException {
	try (BufferedReaderbr =
	new BufferedReader(new FileReader(path))) {
	return br.readLine();
	    }
	}

}

The function readFirstLineFromFile(String) contains theBufferedReader as the resource inside the try statement. Due to this it will be closed regardless of the normal or abrupt completion of try statement. Prior to Java SE 7, finally block could be used to ensure that the resource closes after the completion of its use.

Exceptions thrown by methods

Methods can also handle the exceptions by declaring the expected exceptions after the throws statement in the signature of the function. It ensures that any code that calls the function will know the type of exceptions expected to be thrown beforehand, and can provide the exception handler. Another way to deal with the exceptions thrown by a method, is to rethrow them in the declaration of the calling method. This technique ensures the exceptions get bubbled up along the layers to reach a layer written specifically to handle the exceptions.

Let us compile and execute a code sample to see how it is done.

Listing 8: Sample code with throws statement.

import java.io.*;
import java.net.*;

class ExceptionHandlingThrows {
	public static void main(String[] args){
		try{
			exceptionThrower();
		}catch(MalformedURLException e){
			System.out.println("Caught an exception !!!!!!!!!! URL is malformed");
		}
	}
	
	Private static void exceptionThrower()throws MalformedURLException{
		String address = "htt";
		URL url = new URL(address); //(1) Checked Exception
		System.out.println("Clean up code written after this may be bypassed!!!");
	}
};

Compiling and executing the code in listing 8 gives the following result.

Result of listing 8

Figure 7: Result of listing 8

As shown in listing 8, the function exceptionThrower declares that it can throw a MalformedURLException and any function calling it should either handle it or throw it. We have handled the exception in main function using try-catch. Another way could be to declare the main method as

Public static void main(String[] args) throws  MalformedURLException

This would have delegated the responsibility of exception handling to a level above the main function, i.e. JVM.

Chained Exception

Usually it happens that another exception is thrown in response of an exception. Following code fragment shows this condition.


try{
	//Any valid Java code
}catch(Exception e){
		Throw new  SampleException("Another exception",e);
}

This is the case of chained exception. Following functions and constructors are provided by Throwable class to help in such chained exceptions.

  • ThrowablegetCause(): This function returns the exception that caused the current exception.
  • ThrowableinitCause(Throwable): This function sets the exception passed in the argument as the exception that caused the current exception.
  • Throwable (String, Throwable): This is the constructor for Throwable class, which takes a String message as the argument, along with the Throwable exception as the cause
  • Throwable(Throwable): This creates an exception with the argument exception as the cause of the new exception.

Advantages and Disadvantages of Exceptions

Exceptions in Java provide advantageous due to the following points:

  • Separation of “Regular” code from error handling code: Exceptions allow a programmer to identify the occurrence of an out of ordinary event from the regular execution of code. If exception handling is done using the regular coding then the code would be filled with numerous if - else or any other flow control statements.Using exception handling techniques the code for exception handling remains in the catch block or any other function handling the exceptions.
  • Propagation of Exception up the call stack: The sequence, in which functions get called, is the call stack. In an application it may not be possible to catch the exception at the same place as its occurrence. Using throws the exception can be bubbled up the call stack to be handled at an appropriate level.
  • Grouping of different error types: Using Exception class and its subclasses it is possible to create a group of exceptions and their specialized in handling particular situations.

One of the issues regarding the exception handling, which is criticized regularly, is the use of unchecked exceptions which don’t require the compliance of Catch-or-specify requirement. Generally this condition is abused by wrapping a checked exception inside a Runtime exception and throwing it up the call stack. In such case the programmer gets rid of the obligation to handle the checked exceptions. Another wrong practice is to catch the exception and do nothing about it. These are some of the bad programming practices about the rather useful exception handling techniques provided by Java.

Hope you liked the article, see you next time.



Have total 6+ years of experience in developing enterprise applications using DOT.NET 3.5 and 4.0(C#, VB.NET, ADO.NET, ASP.NET),java, JQuery, JSON, LINQ,WCF, MVC3, MVC4, Silverlight, SQL Server, mobile applications and Oracle etc ...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login