Java Checked and Unchecked Exceptions Examples

In this tutorial, we will learn important checked and unchecked built-in exceptions with examples. If you looking for an exception handling tutorial refer to this complete guide: Exception handling in Java.

Overview

Checked Exceptions

These exceptions are checked at compile-time. It means if a method is throwing a checked exception, it must handle it using a try-catch block or declare it using the throws keyword, else the program will not compile. 

Examples include IOExceptionFileNotFoundException, ClassNotFoundException, and SQLException

Unchecked Exceptions

These exceptions are checked at runtime rather than at compile-time. They're subclasses of RuntimeException and don't need to be declared in a method signature. 

Examples include NullPointerException, ArrayIndexOutOfBoundsException, and ArithmeticException.

1. ArithmeticException

ArithmeticException is a runtime exception in Java that gets thrown when an exceptional arithmetic condition has occurred. In most cases, it is due to an operation that doesn't adhere to mathematical rules and conventions.

In the below example, ArithmeticException occurs when an integer is divided by zero.
package com.javaguides.corejava;

public class ArithmeticExceptionExample {

    public static void main(String[] args) {
        try {
            int result = 30 / 0; // Trying to divide by zero
        } catch (ArithmeticException e) {
            System.err.println("ArithmeticException caught!");
            e.printStackTrace();
        }
    }
}
Output:
ArithmeticException caught!
java.lang.ArithmeticException: / by zero
 at com.javaguides.corejava.ArithmeticExceptionExample.main(ArithmeticExceptionExample
Read more at Java Arithmetic Exception Example

2. ArrayIndexOutOfBoundsException

The ArrayIndexOutOfBoundsException is a runtime exception in Java. It is thrown to indicate that 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.

In this example, if an array is having only 3 elements and we are trying to display -1 or 4th element then it would throw this exception.
package com.javaguides.corejava;

public class ArrayIndexOutOfBounds {

    public static void main(String[] args) {

        int[] nums = new int[] {
            1,
            2,
            3
        };

        try {
            int numFromNegativeIndex = nums[-1]; // Trying to access at negative index
            int numFromGreaterIndex = nums[4]; // Trying to access at greater index
            int numFromLengthIndex = nums[3]; // Trying to access at index equal to size of the array
        } catch (ArrayIndexOutOfBoundsException e) {
            System.err.println("ArrayIndexOutOfBoundsException caught");
            e.printStackTrace();
        }
    }
}
Output:
ArrayIndexOutOfBoundsException caught
java.lang.ArrayIndexOutOfBoundsException: -1
 at com.javaguides.corejava.ArrayIndexOutOfBounds.main(ArrayIndexOutOfBounds.java:10)
Read more at Java ArrayIndexOutOfBoundsException Example

3. ClassCastException

The ClassCastException is a runtime exception that Java throws when code attempts to cast an object to a subclass it doesn't belong to. In simpler terms, it arises when we mistakenly try to treat one type of object as another incompatible type.

Here is a very simple example, an Integer object cannot be cast to a String object:
public class ClassCastExceptionExample {
    public static void main(String[] args) {
        Object obj = new Integer(100);
        System.out.println((String) obj);
    }
}
Output:
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
 at ClassCastExceptionExample.main(ClassCastExceptionExample.java:4)
Read more at ClassCastException Java Example

4. ClassNotFoundException

The ClassNotFoundException is a checked exception that signals the Java Runtime Environment (JRE) cannot find the specified class in its classpath during runtime. It's important to note that this is different from the NoClassDefFoundError, which occurs when the class was available during compile-time but not at runtime.

The below example demonstrates the common causes of java.lang.ClassNotFoundException is using Class.forName or ClassLoader.loadClass to load a class by passing the string name of a class and it’s not found on the classpath.
package com.javaguides.corejava;

public class ClassNotFoundExceptionExample {

    public static void main(String[] args) {

        try {

            Class.forName("com.javaguides.corejava.Demo");

            ClassLoader.getSystemClassLoader().loadClass("com.javaguides.corejava.Demo");

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
Output:
java.lang.ClassNotFoundException: com.javaguides.corejava.Demo
 at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
 at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
 at java.lang.Class.forName0(Native Method)
 at java.lang.Class.forName(Class.java:264)
 at com.javaguides.corejava.ClassNotFoundExceptionExample.main(ClassNotFoundExceptionExample.java:9)
Read more at ClassNotFoundException Java Example

5. FileNotFoundException

FileNotFoundException is a checked exception in Java, which means you're required to handle it, either by catching it or declaring it in the method signature using the throws keyword. It's thrown primarily by the Java I/O system when attempting to access a file that doesn't exist or isn't accessible for some reason.

In the below example, an invalid path location passed to the File constructor leads to this exception.
package com.javaguides.corejava;

import java.io.BufferedReader;

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

public class FileNotFoundExceptionExample {

    public static void main(String[] args) {

        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(new File("/invalid/file/location")));
        } catch (FileNotFoundException e) {
            System.err.println("FileNotFoundException caught!");
            e.printStackTrace();
        }
    }
}
Output:
FileNotFoundException caught!
java.io.FileNotFoundException: \invalid\file\location (The system cannot find the path specified)
 at java.io.FileInputStream.open0(Native Method)
 at java.io.FileInputStream.open(FileInputStream.java:195)
 at java.io.FileInputStream.<init>(FileInputStream.java:138)
 at java.io.FileReader.<init>(FileReader.java:72)
 at com.javaguides.corejava.FileNotFoundExceptionExample.main(FileNotFoundExceptionExample.java:15)
Read more at FileNotFoundException Java Example

6. IllegalStateException

The IllegalStateException is a runtime exception thrown to indicate that a method has been invoked at an inappropriate time, or the Java environment or Java application is not in an appropriate state for the requested operation.

In this example, the Iterator.remove() method throws an IllegalStateException - if the next method has not yet been called, or the remove method has already been called after the last call to the next method.
package com.javaguides.corejava;

import java.util.ArrayList;

import java.util.Iterator;
import java.util.List;

public class IllegalStateExceptionExample {

    public static void main(String[] args) {

        List < Integer > intList = new ArrayList < > ();

        for (int i = 0; i < 10; i++) {
            intList.add(i);
        }

        Iterator < Integer > intListIterator = intList.iterator(); // Initialized with index at -1

        try {
            intListIterator.remove(); // IllegalStateException
        } catch (IllegalStateException e) {
            System.err.println("IllegalStateException caught!");
            e.printStackTrace();
        }
    }
}
Output:
IllegalStateException caught!
java.lang.IllegalStateException
 at java.util.ArrayList$Itr.remove(ArrayList.java:872)
 at com.javaguides.corejava.IllegalStateExceptionExample.main(IllegalStateExceptionExample.java:21)
Read more at IllegalStateException in Java with Example

7. InterruptedException

When a thread is blocked (waiting, sleeping, or occupied with some long-running operations) and another thread interrupts it by invoking its interrupt() method, the blocked thread throws an InterruptedException. This mechanism allows threads to be stopped, queried, and controlled.

In the below example, note that the thread interrupted in the main() method throws an InterruptedException exception that is handled in the run() method.
package com.javaguides.corejava;

class ChildThread extends Thread {

    public void run() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            System.err.println("InterruptedException caught!");
            e.printStackTrace();
        }
    }

}

public class InterruptedExceptionExample {

    public static void main(String[] args) throws InterruptedException {
        ChildThread childThread = new ChildThread();
        childThread.start();
        childThread.interrupt();
    }
}
Output:
InterruptedException caught!
java.lang.InterruptedException: sleep interrupted
 at java.lang.Thread.sleep(Native Method)
 at com.javaguides.corejava.ChildThread.run(InterruptedExceptionExample.java:7)
Read more at InterruptedException in Java with Example

8. NullPointerException

A NullPointerException is a runtime exception thrown by the JVM when the application code tries to access or modify a member (e.g., call a method or access a property) of a null object.

In the below example, the person object is null and we are invoking its fields on the null object leads to NullPointerException.
package com.javaguides.corejava;

public class NullPointerExceptionExample {

    public static void main(String[] args) {

        Person personObj = null;
        try {
            String name = personObj.personName; // Accessing the field of a null object
            personObj.personName = "Ramesh Fadatare"; // Modifying the field of a null object
        } catch (NullPointerException e) {
            System.err.println("NullPointerException caught!");
            e.printStackTrace();
        }

    }
}

class Person {

    public String personName;

    public String getPersonName() {
        return personName;
    }

    public void setPersonName(String personName) {
        this.personName = personName;
    }
}
Output:
NullPointerException caught!
java.lang.NullPointerException
 at com.javaguides.corejava.NullPointerExceptionExample.main(NullPointerExceptionExample.java:9)
Read more at NullPointerException Java Example

9. NumberFormatException

NumberFormatException is a runtime exception in Java that signals an attempt to convert a string into a number, but the string does not have the appropriate format. This typically occurs when using methods like Integer.parseInt() or Double.parseDouble() on strings that don't represent valid numbers.

In the below example, we are trying to parse the "100ABCD" string into integer leads to NumberFormatException:
package com.javaguides.corejava;

public class NumberFormatExceptionExample {

    public static void main(String[] args) {

        String str1 = "100ABCD";
        try {
            int x = Integer.parseInt(str1); // Converting string with inappropriate format
            int y = Integer.valueOf(str1);
        } catch (NumberFormatException e) {
            System.err.println("NumberFormatException caught!");
            e.printStackTrace();
        }
    }
}
Output:
NumberFormatException caught!
java.lang.NumberFormatException: For input string: "100ABCD"
 at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
 at java.lang.Integer.parseInt(Integer.java:580)
 at java.lang.Integer.parseInt(Integer.java:615)
 at com.javaguides.corejava.NumberFormatExceptionExample.main(NumberFormatExceptionExample.java:9)
Read more at NumberFormatException in Java Example

10. ParseException

ParseException is a checked exception in Java and is a member of java.text package. It signals that an error has been reached unexpectedly while parsing. This usually happens when a string fails to match a required format or pattern.

In this example, we use DateFormat.parse(String source) method which throws a ParseException object.
This parse() method throws ParseException - if the beginning of the specified string cannot be parsed.
Here is a complete code to throw a ParseException exception:
package com.javaguides.corejava;

import java.text.DateFormat;

import java.text.ParseException;
import java.text.SimpleDateFormat;

public class ParseExceptionExample {

    public static void main(String[] args) {

        DateFormat format = new SimpleDateFormat("MM, dd, yyyy");

        try {
            format.parse("01, , 2010");
        } catch (ParseException e) {
            System.err.println("ParseException caught!");
            e.printStackTrace();
        }
    }
}
Output:
ParseException caught!
java.text.ParseException: Unparseable date: "01, , 2010"
 at java.text.DateFormat.parse(DateFormat.java:366)
 at com.javaguides.corejava.ParseExceptionExample.main(ParseExceptionExample.java:15)
Read more at ParseException in Java Example

11. StringIndexOutOfBoundsException

StringIndexOutOfBoundsException is a runtime exception thrown when an attempt is made to access an index in the String object that is either negative or greater than or equal to the size of the string.

In the below example, the exception occurred because the referenced index was not present in the String.
package com.javaguides.corejava;

public class StringIndexOutOfBounds {

    public static void main(String[] args) {

        String str = "Hello World";
        try {
            char charAtNegativeIndex = str.charAt(-1); // Trying to access at negative index
            char charAtLengthIndex = str.charAt(11); // Trying to access at index equal to size of the string
        } catch (StringIndexOutOfBoundsException e) {
            System.err.println("StringIndexOutOfBoundsException caught");
            e.printStackTrace();
        }
    }
}
Output:
StringIndexOutOfBoundsException caught
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
 at java.lang.String.charAt(String.java:658)
 at com.javaguides.corejava.StringIndexOutOfBounds.main(StringIndexOutOfBounds.java:9)
Read more at StringIndexOutOfBoundsException in Java with Example

Conclusion

In this tutorial, we have seen important checked and unchecked built-in exceptions with examples. Check out the complete exception handling tutorial at Java Exception Handling Tutorial.

Comments