Types of Exception in Java

HOME

Java defines two categories of exceptions – Built-in Exceptions and User-Defined Exception.

Built-in Exceptions – These exceptions are available in Java libraries. There are various types of exceptions which are suitable to specific type of exception situations.

User-defined or Custom Exceptions – There are several conditions where built-in exceptions in Java is unable to handle certain situations. In such cases, user can create a custom or user defined exception.

In this tutorial, I’ll explain about built-in exceptions.

  1. ArithmeticException

It is thrown when an exception has occurred in an arithmetic operation. Below is an example of this exception.

public class ArithmeticExceptionDemo {

	public static void main(String[] args) {
		{
			try {
				int a = 30, b = 0;
				int c = a / b; // cannot divide by zero
				System.out.println("Result = " + c);
			} catch (ArithmeticException e) {
				System.out.println("Can't divide a number by 0");
			}
		}
	}
}

Output
Can't divide a number by 0

2. ArrayIndexOutOfBoundsException

It is thrown when an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

public class ArrayIndexOutOfBoundsExceptionDemo {

	public static void main(String[] args) {
		{
			try {
				// Create an array of size 5
				int a[] = new int[5];

				// Access 11th element from array of size 5
				a[10] = 9;
			} catch (ArrayIndexOutOfBoundsException e) {
				System.out.println("Array Index is Out Of Bounds");
			}
		}
	}
}

Output
Array Index is Out Of Bounds

3. StringIndexOutOfBoundsException

It is thrown by String class methods to indicate that an index is either negative or greater than the size of the string.

public class StringOutOfBoundDemo {

	public static void main(String[] args) {
		{
			try {
				String a = "This is testing"; // length is 15
				System.out.println("Length of String :" + a.length());

				char b = a.charAt(20); // accessing 20th element
				System.out.println(b);
			} catch (StringIndexOutOfBoundsException e) {
				System.out.println("StringIndexOutOfBoundsException");
			}
		}
	}
}

Output
Length of String :15
StringIndexOutOfBoundsException

4. NullPointerException

This exception is thrown when referring to the members of a null object.

public class NullPointerDemo {

	public static void main(String[] args) {
		{
			try {
				String a = null; // null value
				System.out.println(a.length());
			} catch (NullPointerException e) {
				System.out.println("NullPointerException");
			}
		}
	}
}

Output
NullPointerException

5. NumberFormatException

This exception is thrown when a method can not convert a string into a numeric format.

public class NumberFormatDemo {

	public static void main(String[] args) {
		try {
			// "java" is not a number
			int num = Integer.parseInt("java");

			System.out.println(num);
		} catch (NumberFormatException e) {
			System.out.println("Number format exception");
		}
	}
}

Output
Number format exception

6. FileNotFoundException

This Exception is thrown when a file is not accessible or does not open.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;

public class FileNotFoundDemo {

	public static void main(String[] args) {
		try {

			// Following file does not exist
			File file = new File("C://demofile.txt");

			FileReader fr = new FileReader(file);
		} catch (FileNotFoundException e) {
			System.out.println("File does not exist");
		}
	}
}

Output
File does not exist

7. ClassNotFoundException

This Exception is raised when we try to access a class whose definition is not found.

package JavaDemo;

public class ClassNotFoundExceptionDemo {

	public static void main(String[] args) {
		try {
			Class temp = Class.forName("gfg");
			// Calling the clas gfg which is not present in the
			// current class temp instance of calling class it
			// will throw ClassNotFoundException;
		} catch (ClassNotFoundException e) {
			// block executes when mention exception occur
			System.out.println("Class does not exist check the name of the class");
		}
	}
}

Output
Class does not exist check the name of the class

8. IOException

It is thrown when an input-output operation failed or interrupted.

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

public class IOExceptionDemo {

	public static void main(String[] args) {

		String filepath = "C:\\Users\\SingVi04\\Desktop\\IOTest1.txt";
		BufferedReader br1 = null;
		String curline;

		try {
			br1 = new BufferedReader(new FileReader(filepath));

			while ((curline = br1.readLine()) != null) {
				System.out.println(curline);
			}
		} catch (IOException e) {
			System.err.println("IOException found :" + e.getMessage());
		} finally {
			try {
				if (br1 != null)
					br1.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

Output
IOException found :C:\Users\SingVi04\Desktop\IOTest1.txt (The system cannot find the file specified)

9. NoSuchMethodException

It is thrown when accessing a method which is not found.

10. InterruptedException

It is thrown when a thread is waiting , sleeping , or doing some processing , and it is interrupted.

11. NoSuchFieldException

It is thrown when a class does not contain the field (or variable) specified.

12. RuntimeException

This represents any exception which occurs during runtime. They are ignored during compilation time. Such as logical bugs.

import java.util.Scanner;

public class RunTimeDemo {

	public static void main(String[] args) {
		// Reading user input
		Scanner input_dev = new Scanner(System.in);
		System.out.print("Enter your age in Numbers: ");
		int age1 = input_dev.nextInt();
		if (age1 > 20) {
			System.out.println("You can view the page");
		} else {
			System.out.println("You cannot view the page");
		}
	}
}
Output

Enter your age in Numbers: 25
You can view the page

Output

Enter your age in Numbers: two
Exception in thread "main" java.util.InputMismatchException
	at java.base/java.util.Scanner.throwFor(Scanner.java:939)
	at java.base/java.util.Scanner.next(Scanner.java:1594)
	at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
	at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
	at JavaDemo.RunTimeDemo.main(RunTimeDemo.java:11)

13. SQLException

This type of exception occurs while executing queries on a database related to the SQL syntax.

14. IllegalArgumentException

It is thrown when an inappropriate and incorrect argument is passed to the method. Suppose, a method does not allow null, but we are providing null as the parametr, then this exception is thrown.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s