List of Checked Exception in Java

In this post, we’ll look at lis of checked exception in Java and how they can help you write more robust and dependable programs.

Checked Exception in Java

List of Common Checked Exception in Java

ClassNotFoundException

This checked exception is thrown when an application tries to load in a class but no definition for the class with the specified name could be found.

public class ClassNotFoundExceptionExample {
    public static void main(String[] args) {
        try {
            // Trying to load a class that doesn't exist
            Class<?> nonExistentClass = Class.forName("NonExistentClass");
        } catch (ClassNotFoundException e) {
            System.out.println("ClassNotFoundException caught: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

CloneNotSupportedException

This checked exception in Java is thrown to indicate that the clone method in class Object has been called to clone an object, but that the object’s class does not implement the Cloneable interface.

class MyClass implements Cloneable {
    private int value;

    public MyClass(int value) {
        this.value = value;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

public class CloneNotSupportedExceptionExample {
    public static void main(String[] args) {
        try {
            MyClass originalObject = new MyClass(10);
            
            // Attempting to clone the object
            MyClass clonedObject = (MyClass) originalObject.clone();
            
            System.out.println("Original value: " + originalObject.hashCode());
            System.out.println("Cloned value: " + clonedObject.hashCode());
        } catch (CloneNotSupportedException e) {
            System.out.println("CloneNotSupportedException caught: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

IOException

This checked exception in Java signals that an I/O exception of some sort has occurred. This class is the general class of exceptions produced by failed or interrupted I/O operations.

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

public class IOExceptionExample {
    public static void main(String[] args) {
        BufferedReader reader = null;
        try {
            // Opening a file for reading
            reader = new BufferedReader(new FileReader("sample.txt"));
            
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.out.println("IOException caught: " + e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                System.out.println("IOException in finally block: " + e.getMessage());
                e.printStackTrace();
            }
        }
    }
}

InterruptedException

This checked exception in java is thrown when a thread is waiting, sleeping, or otherwise occupied, and the thread is interrupted, either before or during the activity.

public class InterruptedExceptionExample {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            try {
                System.out.println("Thread started");
                Thread.sleep(2000); // Simulating some time-consuming task
                System.out.println("Thread completed");
            } catch (InterruptedException e) {
                System.out.println("InterruptedException caught: " + e.getMessage());
                e.printStackTrace();
            }
        });

        thread.start();

        try {
            Thread.sleep(1000); // Main thread sleeps for a while
            thread.interrupt(); // Interrupting the thread
        } catch (InterruptedException e) {
            System.out.println("Main thread InterruptedException: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

FileNotFoundException

This checked exception signals that an attempt to open the file denoted by a specified pathname has failed.

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

public class FileNotFoundExceptionExample {
    public static void main(String[] args) {
        try {
            BufferedReader reader = new BufferedReader(new FileReader("nonexistent-file.txt"));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            reader.close();
        } catch (FileNotFoundException e) {
            System.out.println("FileNotFoundException caught: " + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("IOException caught: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

ParseException

This checked exception in Java signals that an error has been reached unexpectedly while parsing.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ParseExceptionExample {
    public static void main(String[] args) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = "2023-08-10";

        try {
            Date date = dateFormat.parse(dateString);
            System.out.println("Parsed Date: " + date);
        } catch (ParseException e) {
            System.out.println("ParseException caught: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

InstantiationException and IllegalAccessException

InstantiationException – Thrown when an application tries to create an instance of a class using the newInstance method in class Class,  but the specified class object cannot be instantiated.

IllegalAccessException – An IllegalAccessException is thrown when an application tries to reflectively create an instance (other than an array), set or get a field, or invoke a method, but the currently executing method does not have access to the definition of the specified class, field, method or constructor.

class ExampleClass {
    private int value;

    public ExampleClass(int value) {
        this.value = value;
    }
}

public class InstantiationExceptionAndIllegalAccessExceptionExample {
    public static void main(String[] args) {
        try {
            // Attempting to create an instance of a class with a private constructor
            ExampleClass example = ExampleClass.class.newInstance();
        } catch (InstantiationException e) {
            System.out.println("InstantiationException caught: " + e.getMessage());
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            System.out.println("IllegalAccessException caught: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

NoSuchFieldException and NoSuchMethodException

NoSuchFieldException – Signals that the class doesn’t have a field of a specified name.
NoSuchMethodException – Thrown when a particular method cannot be found.

import java.lang.reflect.Field;
import java.lang.reflect.Method;

class MyClass {
    private int value;

    public void myMethod() {
        System.out.println("This is myMethod.");
    }
}

public class NoSuchFieldAndMethodExceptionExample {
    public static void main(String[] args) {
        try {
            // Attempting to access a non-existent field
            Class<?> myClass = MyClass.class;
            Field nonexistentField = myClass.getDeclaredField("nonexistentField");

            // Attempting to access a non-existent method
            Method nonexistentMethod = myClass.getMethod("nonexistentMethod");

        } catch (NoSuchFieldException e) {
            System.out.println("NoSuchFieldException caught: " + e.getMessage());
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            System.out.println("NoSuchMethodException caught: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
Some more Checked Exceptions
Screen Shot 2020-04-18 at 9.05.29 PM

Conclusion: List of Checked Exception in Java

Understanding checked exceptions in Java is critical for writing dependable programming. These exceptions alert developers to potential problems that demand quick attention, allowing them to handle mistakes gracefully and preserve the reliability of their programs. We looked at a list of common checked exception in Java, each with its own context and relevance.

Read More: All about Java Exceptions

Leave a Reply

Your email address will not be published. Required fields are marked *