Exceptions are the unwanted events, that occurs during program execution. Exception stops the current program execution, creates an exception object and returns it back to the called program. The exception object contains information about type of exception and where the error has occurred in the program and other error related information. We can also create a custom exception object and throw it.

exceptions in java

If an exception occurs in a method, run time system will check if any exception handling is present in current method. If no handler is found, exception is passed to the caller program. If the caller program does not provide any exception handling mechanism, run time system will search for previous level and finally if no handler is present in any of the call stack, program execution gets terminated.

In java there are tree kinds of exceptions which are given below.

  • Checked Exceptions : These are anticipated exception that could be possibly thrown by the program. A proper exception handling should be provided for checked exceptions.
  • Errors : These are exceptional scenario’s which may occur which may not be anticipated by the application. This is categorized as Unchecked Exception.
  • Run time Exceptions : These are the exceptions which are internal to the application, but applications usually can not anticipate or recover from. This type of exception also comes under Unchecked Exception.

Handling exceptions with try, catch and finally blocks

We need to surround the program, which may throw exceptions within try block. To handle the exception, which occurs within the try block, we should add a catch block next to try block. We can have multiple catch  blocks, each block handling particular exception. A finally block is always executed if there is a try block. We can add cleanup code inside the finally block.

Following example shows a simple program with try, catch and finally blocks. Here, we are trying to read a file file.txt using FileInputStream, which throws IOException if given file is not found. Exception is handled at catch block and finally block always executes irrespective of occurrence of exception.

import java.io.FileInputStream;
import java.io.IOException;
public class ExceptionTest {
	public static void main(String args[]){
		try {	
		    FileInputStream fis = new FileInputStream("file.txt");
		    fis.close();
		} catch (IOException e) {
			System.out.println("Exception occuured!!");
		} finally {
			System.out.println("Finally block reached!!");
		}
	}
}

Using throws keyword : Consider that, we are writing a method, which throws a checked exception. If our method is used by different users and they may want to handle this exception in different ways. In this scenario, we can specify the method with throws keyword and the type of exception it may through, and exception is then handled by the users of the method.

Following example shows the usage of throws keyword.

public void readFile() throws IOException {
   fis = new FileInputStream("file.txt");
   fis.close();
}

The throw keyword to throw an exception : Using throw keyword, we can throw an exception. This statement requires a throwable object. Which means that the exception object should inherit the Throwable class. We can also create custom exception classes and throw them.

Example 

throw new ArithmeticException();

Chained Exceptions : If another exception is thrown in response to an exception, we can use chained exception to pass information about initial exception to the next level. This is useful when we have multiple methods chained together and each of them throwing their own type of exception. Now using chained exception, exception occurred in one method is handled in another method by throwing another exception, which is more suitable one, without loosing the initial cause of the exception. chained exception provides getCause() method to get the initial cause for exception. initCause(Throwable cause) method can be used to set the initial cause of exception, before throwing a new one. Also there are two constructors available in Throwable class for chained exception, which allows to set the cause.Those constructors are : Throwable(Throwable cause) and Throwable(String message, Throwable cause).

Using Exception in programming provides advantages like separation of error handling code from regular flow, differentiating and grouping the errors based on their types and propagating the error up the caller stack if multiple levels are involved, etc. Handling the errors and exceptions is always a best practice.

In  this article, we learned about exception handling in Java, types of exceptions, usage of try, catch, finally blocks to handle the exceptions, throwing the exceptions, advantages of exceptions, etc.

Also read :