Java Exception Handling Introduction

What is an Exception ?

Exception is an abnormal/un-expected/un-wanted event occurred in the execution of the program that disturb the normal flow of execution.

Technically an exception is a class and an Object in Java.

What is Exception Handling ?

Exception Handling doesn’t mean repairing an Exception.

Exception Handling means defining an alternative way to continue the rest of the program normally even an Exception raised in the execution of the program.

Example Scenario : Suppose there is search functionality in an application. Let’s assume that, how many search results we need to read from the database is defined in one config file. What if, We failed to read that config file? If file reading fails, then it will throw FileNotFoundException. So the application gets terminated. That means even the code which is not related to ‘reading config file’ also will not be executed. Here exactly we need Exception Handling. So, when we hit with the FileNotFoundException, We need to catch exception and define alternate value and make sure the remaining code of the application would execute. This way of defining alternative is nothing but Exception Handling.

Example – Exception Handling

package com.vidvaan.corejava.exception01.introduction;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;

// Exception Handling Program
public class ExceptionHandlingDemo {
	public static void main(String[] args) {
		System.out.println("main begin");

		System.out.println("Finding value for : numberOfRecordsToRead");
		int numberOfRecordsToRead = -1;
		try {
			// Reading config.txt file to get value for numberOfRecordsToRead
			Path filePath = Paths.get("config.txt");
			Scanner scanner = new Scanner(filePath);
			if (scanner.hasNext()) {
				numberOfRecordsToRead = scanner.nextInt();
			}
		} catch (IOException e) {
			// Assigning default value 10 when file reading failed
			System.out.println("Exception raised while reading config.txt");
			numberOfRecordsToRead = 10;
		}
		System.out.println("numberOfRecordsToRead : " + numberOfRecordsToRead);

		// This final statement also executes even exception is raised, Because
		// exception is handled
		System.out.println("main end");
	}
}

Output :

main begin
Finding value for : numberOfRecordsToRead
Exception raised while reading config.txt
numberOfRecordsToRead : 10
main end

In the above example, If file reading fails, we defined an alternative value to the variable(numberOfRecordsToRead). So, even file reading fails, still application executes till the end(without abnormal termination).

When an Exception occurs ?

When java program violates JVM rules then Exception occurs. Some of the JVM rules listed below.

  • Perform operations on bad data(Unchecked/Run-time Exception)
    • call methods on null
    • divide by zero
    • Access invalid index of an array
    • convert alphabets to number … etc.
  • External resources unavailability(Checked/Compile-time Exception)
    • File is not available to read
    • Database connection is failed
    • JMS connection is failed … etc.
  • Lack of System resources(Error)
    • Memory is not sufficient
    • Stack memory over flows … etc.

Who will throw an Exception ?

JVM will throw an Exception when JVM rules are violated. In our application code ‘throw’ keyword is not required to throw an exception by JVM.

Can we(developer) throw an Exception ?

Yes we(developer) can throw exception when business rules are violated. In our application code ‘throw’ keyword is required to throw an exception by Developer.

What Exception thrown by JVM when JVM rules are violated ?

For every JVM rule violation, JVM has defined one exception. For Example if you try to perform operation on null then it will throw NullPointerException, If you try to divide with zero it will throw ArithmeticException. Like wise for every violation JVM throws specific exception.

What is an Exception Object ?

An Exception object is an instance of any Exception class(NullPointerException or ArithmeticException or IOException …etc.). It gets created and hand over to the Java runtime when JVM rule is violated.

What is encapsulated in an Exception Object ?

The exception object contains name, description and Call Stack of the exception. When we print the exception all these(name, description and call stack) together will be printed, It is also known as exception stack trace

Scroll to Top