Java Exceptions Tutorial: Built-in and User-defined Exceptions

HOME

Table of Contents

  1. These are exceptions that are checked at compile-time.
  2. They must be either handled using a try-catch block or declared in the method signature using the `throws` keyword.
  3. Examples include IOException, SQLException, and FileNotFoundException.

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");
			}
		}
	}
}

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");
			}
		}
	}
}

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");
			}
		}
	}
}

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");
			}
		}
	}
}

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");
		}
	}
}

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");
		}
	}
}

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");
		}
	}
}

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\\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();
			}
		}
	}
}

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");
		}
	}
}

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 comment