Built-in Exceptions in Java with Examples
Built-in exceptions in Java libraries are exceptions that are already provided and can be used to handle specific error situations. These exceptions help us understand the cause of the error. They can be classified into two main categories: checked exceptions and unchecked exceptions.
Checked Exceptions:
Compile-time exceptions are referred to as checked exceptions since they undergo examination during the compilation process by the compiler. It is the responsibility of the compiler to verify whether the programmer has appropriately handled the exception. The programmer must handle the exception; otherwise, a compilation error will be displayed by the system.
The checked built-in exceptions are:
- ClassNotFoundException
- InterruptedException
- IOException
- InstantiationException
- FileNotFoundException
ClassNotFoundException:
The name implies that if the class is not found, a ClassNotFound exception will occur. This exception is thrown when a Java Virtual Machine (JVM) attempts to load a particular class, but that class cannot be found in the designated classpath. But, the classpath is invalid.
Implementation:
FileName: ClassNotFoundExceptionExample.java
import java.io.*;
import java.util.*;
public class ClassNotFoundExceptionExample
{
public static void main(String args[])
{
// To identify exceptions, try block is used
try {
Class.forName("Hello!, Welcome to the world");
}
// Catch block for managing exceptions
catch (ClassNotFoundException e)
{
// Printing exceptions and the line number on the terminal
// with the printStackTrace() method
e.printStackTrace();
}
}
}
Output:
java.lang.ClassNotFoundException: Hello!, Welcome to the world
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:390)
at java.base/java.lang.Class.forName(Class.java:381)
at ClassNotFoundExceptionExample.main(ClassNotFoundExceptionExample.java:10)
InterruptedException:
The InterruptedException is a type of checked exception that is thrown when a thread, which is either sleeping, waiting, or engaged in a lengthy operation, gets interrupted. The primary objective of this exception is to signal that the current thread should cease its ongoing task and address the interruption, typically by terminating.
Implementation:
FileName: InterruptedExceptionExample.java
import java.io.*;
import java.util.*;
public class InterruptedExceptionExample
{
public static void main(String[] args)
{
Thread SleepingThread = new Thread(() ->
{
// to identify exceptions
try {
// Using sleep to simulate a long process
System.out.println("Going to sleep...");
Thread.sleep(15000); // thread is Sleeping for 15 seconds
System.out.println("Thread woke up normally!");
}
// managing of the exceptions
catch (InterruptedException ex) {
ex.printStackTrace();
System.err.println("Thread interrupted while sleeping!");
}
});
SleepingThread.start();
// The SleepingThread will be interrupted by
// the main thread after five seconds of sleep.
try {
Thread.sleep(5000);
}
catch (InterruptedException ignored) { }
SleepingThread.interrupt();
}
}
Output:
Going to sleep...
java.lang.InterruptedException: sleep interrupted
at java.base/java.lang.Thread.sleep(Native Method)
at InterruptedExceptionExample.lambda$main$0(InterruptedExceptionExample.java:13)
at java.base/java.lang.Thread.run(Thread.java:829)
Thread interrupted while sleeping!
IOException:
The occurrence of an I/O error triggers the throwing of an IOException, which is an exception specifically designed for this purpose. This exception serves as the foundation for other exceptions that arise when reading or accessing files, directories, and streams.
The IOException is categorized as a checked exception, meaning it is thrown during compile-time. Resolving checked exceptions is imperative in order to execute a Java program successfully.
Implementation:
FileName: IOExceptionExample.java
import java.util.*;
import java.io.*;
public class IOExceptionExample
{
public static void main(String args[])
{
FileInputStream file = null;
file = new FileInputStream("Hello.txt");
int i;
while ((i = file.read()) != -1)
{
System.out.print((char)i);
}
file.close();
}
}
Output:
IOExceptionExample.java:8: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
file = new FileInputStream("Hello.txt");
^
IOExceptionExample.java:10: error: unreported exception IOException; must be caught or declared to be thrown
while ((i = file.read()) != -1)
^
IOExceptionExample.java:14: error: unreported exception IOException; must be caught or declared to be thrown
file.close();
^
3 errors
InstantiationException:
The InstantiationException is a runtime exception in Java that arises when an application endeavors to generate an instance of a class using the Class.newInstance() method. Still, the designated class object cannot be instantiated.
Implementation:
FileName: InstantiationExceptionExample.java
import java.io.*;
import java.util.*;
public class InstantiationExceptionExample
{
public static void main(String[] args)
{
try {
Class<Boolean> c = boolean.class;
c.newInstance();
}
//Here, it manages both InstantiationException and IllegalAccessException
catch (InstantiationException ie)
{
ie.printStackTrace();
}
catch (IllegalAccessException ae) {
ae.printStackTrace();
}
}
}
Output:
java.lang.InstantiationException: boolean
at java.base/java.lang.Class.newInstance(Class.java:571)
at InstantiationExceptionExample.main(InstantiationExceptionExample.java:9)Caused by: java.lang.NoSuchMethodException: boolean.<init>()
at java.base/java.lang.Class.getConstructor0(Class.java:3349)
at java.base/java.lang.Class.newInstance(Class.java:556)
... 1 more
FileNotFoundException:
The java.io.FileNotFoundException is a checked exception in Java that arises when there is a failure in opening a file indicated by a given pathname. This particular exception is thrown by the constructors of FileInputStream, FileOutputStream, and RandomAccessFile when a file with the specified pathname is either not present or cannot be accessed.
Due to the fact that FileNotFoundException is a checked exception, it is necessary to handle it explicitly in methods that have the potential to throw this exception. This can be done by either utilizing a try-catch block or by throwing it using the throws clause.
Implementation:
FileName: FileNotFoundExceptionExample.java
import java.io.*;
import java.util.*;
public class FileNotFoundExceptionExample
{
public static void main(String args[])
{
BufferedReader b = null;
try {
b = new BufferedReader(new FileReader("Hello.txt"));
String data = null;
while ((data = b.readLine()) != null)
{
System.out.println(data);
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try {
if (b != null)
{
b.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Output:
java.io.FileNotFoundException: Hello.txt (No such file or directory)at java.base/java.io.FileInputStream.open0(Native Method)
at java.base/java.io.FileInputStream.open(FileInputStream.java:219)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:157)at java.base/java.io.FileInputStream.<init>(FileInputStream.java:112)at java.base/java.io.FileReader.<init>(FileReader.java:60)
at FileNotFoundExceptionExample.main(FileNotFoundExceptionExample.java:9)
Unchecked Exceptions:
The contrary of checked exceptions is an unchecked exception. The compiler does not check these exceptions during compile time. To put it another way, a program won't generate a compilation error if it throws an unchecked exception and we neglect to manage or declare it. This usually occurs when a user interacts with the program and enters inaccurate data.
The unchecked exceptions are:
- ArithemeticException
- ClassCastException
- NullPointerException
- ArrayIndexOutOfBoundsException
- ArrayStoreException
- IllegalThreadStorageException
ArithemeticException:
An arithmetic exception is an atypical result or unchecked error that occurs in the code when an incorrect mathematical or arithmetic operation is encountered during runtime. This runtime problem, known as an exception, occurs when the denominator of a fraction is 0, causing the JVM to be unable to determine the result. As a result, the program execution is halted, and an exception is triggered.
Implementation:
FileName: ArithmeticExceptionExample.java
import java.io.*;
import java.util.*;
public class ArithmeticExceptionExample
{
void division(int x, int y)
{
// performing the division and saving the result
int res = x / y;
System.out.println("Division operation has been executed successfully.");
System.out.println("Result after performing the division operation: " + res);
}
public static void main(String argvs[])
{
// Creating an instance of the ArithmeticException type
ArithmeticExceptionExample obj = new ArithmeticExceptionExample();
obj.division(4, 0);
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero at ArithmeticExceptionExample.division(ArithmeticExceptionExample.java:8)
at ArithmeticExceptionExample.main(ArithmeticExceptionExample.java:16)
ClassCastException:
As ClassCastException is a subclass of RuntimeException, it is an unchecked exception. When an incorrect typecast occurs—for example, when an object is attempted to be typecast from a parent type to a child type or from an object to a subclass of which it is not an instance, then the JVM raises this exception automatically.
Implementation:
FileName: ClassCastExceptionExample.java
import java.io.*;
import java.lang.*;
import java.util.*;
public class ClassCastExceptionExample
{
public static void main(String[] args)
{
try {
// creation of an object
Object obj = new Object();
// The object obj is typecast to a string,
// which raises the classcasted error since
// we are type casting a parent type to a child type.
String str = (String)obj;
System.out.println(str);
}
catch (Exception ex) {
System.out.println(ex);
}
}
}
Output:
java.lang.ClassCastException: class java.lang.object cannot be cast to class java.lang.String (java.lang.Object and java.lang.String are in module java.base of loader 'bootstrap')
NullPointerException:
A runtime exception is a null pointer exception. One unique type of value that can be applied to an object's reference is null. The NullPointerException is raised any time a reference with the value null is attempted to be used.
Implementation:
FileName: NullPointerException.java
import java.io.*;
import java.lang.*;
import java.util.*;
public class NullPointerException
{
// calling a method by using the object that has the null value
// that throws the NullPointerException
public void foo()
{
System.out.println("Present in the method foo.");
}
public static void main(String args[])
{
NullException o = null; // assigning of the null value
// invoking the method foo()
o.foo();
}
}
Output:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "NullException.foo()" because "<local1>" is nullat NullException.main(NullException.java:16)
ArrayIndexOutOfBoundsException:
The ArrayIndexOutOfBoundsException is raised if an item in an array is attempted to be accessed at an index that does not exist in the array. Stated otherwise, the index could be more than or equal to the array's size.
An implementation of the Serializable interface, the ArrayIndexOutOfBoundsException is a subclass of the IndexOutOfBoundsException.
Implementation:
FileName: ArrayIndexOutOfBoundException.java
import java.io.*;
import java.lang.*;
import java.util.*;
public class ArrayIndexOutOfBoundException
{
public static void main(String[] args) {
String[] array = {"JOHN","SMITH","VIRAJ","DAS"};
//Declaring 4 elements in the String array
for(int i=0;i<=array.length;i++)
{
// In this case, there isn't an element at iteration number array.length, or 4.
System.out.println(array[i]);
// Thus, at iteration 4, it will throw an ArrayIndexOutOfBoundException.
}
}
}
Output:
JOHN
SMITH
VIRAJ
DAS
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4
at ArrayIndexOutOfBoundException.main(ArrayIndexOutOfBoundException.java:12)
ArrayStoreException:
In Java, an ArrayStoreException occurs if an incorrect type of object is attempted to be stored in an array of objects. The ArrayStoreException is a type of exception that is thrown at runtime since it is an extension of RuntimeException.
ArrayStoreException constructors:
ArrayStoreException(): This function creates an instance of the exception without a detail message.
ArrayStoreException(String s): This function creates an instance of ArrayStoreException and passes in the message s.
Implementation:
FileName: ArrayStoreExceptionExample.java
import java.io.*;
import java.lang.*;
import java.util.*;
public class ArrayStoreExceptionExample
{
public static void main(String args[])
{
// Only Double type numbers can be placed in this array
// because the Double class extends the Number class.
Number[] arr = new Double[5];
// trying to use this Double type array to store an integer value
arr[0] = new Integer(10);
}
}
Output:
Exception in thread "main" java.lang.ArrayStoreException: java.lang.Integer
at ArrayStoreExceptionExample.main(ArrayStoreExceptionExample.java:12)
IllegalThreadStorageException:
As IllegalStateException is a subclass of RuntimeException, it is not verified. This exception is raised specifically to show that a method has been called at the incorrect time by the programmer or the API developer. This technique is typically used to show when a method is called at an unauthorized or unsuitable time.
Implementation:
FileName: ThreadRun.java
import java.io.*;
import java.lang.*;
import java.util.*;
public class ThreadRun implements Runnable
//Putting the Runnable interface into action
{
public void run() // Point of entry for a new thread
{
for(int i=0;i<8;i++)
{
System.out.println(i);
}
}
public static void main(String... ar)
{
ThreadRun newThread= new ThreadRun();
Thread th= new Thread(newThread, "Thread2");
// Invoking the constructor of the thread and providing
// the name of the new thread along with the object of
// the class that implements the Runnable interface.
// Declaring the second thread.
th.start();
// IllegalStateException raised when thread (Thread2) is started again while it is already executing.
th.start();
// Due to IllegalStateException halting the main thread, this won't be printed.
System.out.println("Main Thread is halted");
}
}
Output:
0Exception in thread "main"
1
2
3
4
5
6
7
java.lang.IllegalThreadStateException
at java.base/java.lang.Thread.start(Thread.java:789)
at ThreadRun.main(ThreadRun.java:24)