Built-in Exceptions in Java with examples
Last Updated :
03 Jul, 2024
Types of Exceptions in Java Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are suitable to explain certain error situations. Below is the list of important built-in exceptions in Java.
Examples of Built-in Exception:
1. Arithmetic exception : It is thrown when an exceptional condition has occurred in an arithmetic operation.
Java
// Java program to demonstrate
// ArithmeticException
class ArithmeticException_Demo {
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");
}
}
}
OutputCan't divide a number by 0
2. ArrayIndexOutOfBounds Exception: 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.
Java
// Java program to demonstrate
// ArrayIndexOutOfBoundException
class ArrayIndexOutOfBound_Demo {
public static void main(String[] args) {
try {
int[] a = new int[5];
a[5] = 9; // accessing 6th element in an array of
// size 5
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index is Out Of Bounds");
}
}
}
OutputArray Index is Out Of Bounds
3. ClassNotFoundException : This Exception is raised when we try to access a class whose definition is not found.
Java
// Java program to illustrate the
// concept of ClassNotFoundException
class Bishal {
}
class Geeks {
}
class MyClass {
public static void main(String[] args) {
try {
Object o = Class.forName(args[0]).newInstance();
System.out.println("Class created for " + o.getClass().getName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
System.out.println("Exception occurred: " + e.getMessage());
}
}
}
Output:
ClassNotFoundException
4. FileNotFoundException : This Exception is raised when a file is not accessible or does not open.
Java
// Java program to demonstrate
// FileNotFoundException
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
class File_notFound_Demo {
public static void main(String[] args) {
try {
// Following file does not exist
File file = new File("file.txt");
FileReader fr = new FileReader(file);
} catch (FileNotFoundException e) {
System.out.println("File does not exist");
}
}
}
OutputFile does not exist
5. IOException : It is thrown when an input-output operation failed or interrupted
JAVA
// Java program to illustrate IOException
import java.io.*;
class Geeks {
public static void main(String[] args) {
try {
FileInputStream f = new FileInputStream("abc.txt");
int i;
while ((i = f.read()) != -1) {
System.out.print((char)i);
}
f.close();
} catch (IOException e) {
System.out.println("IOException occurred: " + e.getMessage());
}
}
}
Output:
error: unreported exception IOException; must be caught or declared to be thrown
6. InterruptedException : It is thrown when a thread is waiting, sleeping, or doing some processing, and it is interrupted.
JAVA
// Java Program to illustrate
// InterruptedException
class Geeks {
public static void main(String args[])
{
Thread t = new Thread();
t.sleep(10000);
}
}
Output:
error: unreported exception InterruptedException; must be caught or declared to be thrown
7. NoSuchMethodException : t is thrown when accessing a method which is not found.
JAVA
// Java Program to illustrate
// NoSuchMethodException
class Geeks {
public Geeks() {
try {
Class<?> i = Class.forName("java.lang.String");
try {
i.getMethod("someMethod", Class[].class);
} catch (SecurityException | NoSuchMethodException e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new Geeks();
}
}
}
Output:
error: exception NoSuchMethodException is never thrown
in body of corresponding try statement
8. NullPointerException : This exception is raised when referring to the members of a null object. Null represents nothing
JAVA
// Java program to demonstrate NullPointerException
class NullPointer_Demo {
public static void main(String[] args) {
try {
String a = null; // null value
System.out.println(a.charAt(0));
} catch (NullPointerException e) {
System.out.println("NullPointerException..");
}
}
}
Output:
NullPointerException..
9. NumberFormatException : This exception is raised when a method could not convert a string into a numeric format.
JAVA
// Java program to demonstrate
// NumberFormatException
class NumberFormat_Demo {
public static void main(String[] args) {
try {
// "akki" is not a number
int num = Integer.parseInt("akki");
System.out.println(num);
} catch (NumberFormatException e) {
System.out.println("Number format exception");
}
}
}
Output:
Number format exception
10. StringIndexOutOfBoundsException : It is thrown by String class methods to indicate that an index is either negative than the size of the string.
JAVA
// Java program to demonstrate
// StringIndexOutOfBoundsException
class StringIndexOutOfBound_Demo {
public static void main(String[] args) {
try {
String a = "This is like chipping "; // length is 22
char c = a.charAt(24); // accessing 25th element
System.out.println(c);
} catch (StringIndexOutOfBoundsException e) {
System.out.println("StringIndexOutOfBoundsException");
}
}
}
Output:
StringIndexOutOfBoundsException
Some other important Exceptions
1. ClassCastException
JAVA
// Java Program to illustrate
// ClassCastException
class Test {
public static void main(String[] args) {
String s = "Geeks";
Object o = s;
try {
String s1 = (String) new Object();
} catch (ClassCastException e) {
System.out.println("ClassCastException occurred: " + e.getMessage());
}
}
}
Output:
Exception in thread "main" java.lang.ClassCastException:
java.lang.Object cannot be cast to java.lang.String
2. StackOverflowError
JAVA
// Java Program to illustrate
// StackOverflowError
class Test {
public static void main(String[] args)
{
m1();
}
public static void m1()
{
m2();
}
public static void m2()
{
m1();
}
}
Output:
Exception in thread "main" java.lang.StackOverflowError
3. NoClassDefFoundError
JAVA
public class NoClassDefFoundErrorExample {
public static void main(String[] args) {
try {
// Trying to create an instance of a class that doesn't exist
MyNonExistentClass obj = new MyNonExistentClass();
} catch (NoClassDefFoundError e) {
System.out.println("NoClassDefFoundError occurred: " + e.getMessage());
}
}
}
Output:
Note: If the corresponding Test.class file is not found
during compilation then we will get Run-time Exception
saying Exception in thread "main" java.lang.NoClassDefFoundError
4. ExceptionInInitializerError
Code 1:
JAVA
// Java Program to illustrate
// ExceptionInInitializerError
class Test {
static int x = 10 / 0;
public static void main(String[] args)
{
}
}
Output:
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.ArithmeticException: / by zero
Code 2 :
JAVA
// Java Program to illustrate
// ExceptionInInitializerError
class Test {
static
{
String s = null;
System.out.println(s.length());
}
public static void main(String[] args)
{
}
}
Output:
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.NullPointerException
Explanation : The above exception occurs whenever while executing static variable assignment and static block if any Exception occurs.
5. IllegalArgumentException
JAVA
// Java Program to illustrate
// IllegalArgumentException
class Test {
public static void main(String[] args)
{
Thread t = new Thread();
Thread t1 = new Thread();
t.setPriority(7); // Correct
t1.setPriority(17); // Exception
}
}
Output:
Exception in thread "main" java.lang.IllegalArgumentException
Explanation:The Exception occurs explicitly either by the programmer or by API developer to indicate that a method has been invoked with Illegal Argument.
6. IllegalThreadStateException
JAVA
// Java Program to illustrate
// IllegalStateException
class Test {
public static void main(String[] args)
{
Thread t = new Thread();
t.start();
t.start();
}
}
Output:
Exception in thread "main" java.lang.IllegalThreadStateException
Explanation : The above exception rises explicitly either by programmer or by API developer to indicate that a method has been invoked at wrong time.
7. AssertionError
JAVA
// Java Program to illustrate
// AssertionError
class Test {
public static void main(String[] args) {
int x = 5;
// If x is not greater than or equal to 10
// then we will get the AssertionError
assert (x >= 10) : "x is less than 10";
}
}
Output:
Exception in thread "main" java.lang.AssertionError
Explanation : The above exception rises explicitly by the programmer or by API developer to indicate that assert statement fails.
IllegalArgumentException: This exception is thrown when an illegal argument is passed to a method.
For example:
Java
public class IllegalArgumentExceptionExample {
public static void main(String[] args) {
try {
// Trying to pass an invalid argument to a method
calculateArea(-5.0);
} catch (IllegalArgumentException e) {
System.out.println("IllegalArgumentException occurred: " + e.getMessage());
}
}
public static void calculateArea(double radius) {
if (radius < 0) {
// Throwing an IllegalArgumentException with a custom message
throw new IllegalArgumentException("Radius cannot be negative");
}
double area = Math.PI * radius * radius;
System.out.println("Area: " + area);
}
}
OutputIllegalArgumentException occurred: Radius cannot be negative
FileNotFoundException: This exception is thrown when a file cannot be found.
For example:
Java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class FileNotFoundExceptionExample {
public static void main(String[] args) {
try {
// Trying to read a file that doesn't exist
readFile("non-existent-file.txt");
} catch (FileNotFoundException e) {
System.out.println("FileNotFoundException occurred: " + e.getMessage());
} catch (IOException e) {
System.out.println("IOException occurred: " + e.getMessage());
}
}
public static void readFile(String fileName) throws FileNotFoundException, IOException {
File file = new File(fileName);
FileInputStream fis = new FileInputStream(file);
// Read the contents of the file
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
// Process the read bytes
System.out.println("Read " + bytesRead + " bytes.");
}
fis.close();
}
}
OutputFileNotFoundException occurred: non-existent-file.txt (No such file or directory)
Similar Reads
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
TCP/IP Model The TCP/IP model (Transmission Control Protocol/Internet Protocol) is a four-layer networking framework that enables reliable communication between devices over interconnected networks. It provides a standardized set of protocols for transmitting data across interconnected networks, ensuring efficie
7 min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Basics of Computer Networking A computer network is a collection of interconnected devices that share resources and information. These devices can include computers, servers, printers, and other hardware. Networks allow for the efficient exchange of data, enabling various applications such as email, file sharing, and internet br
14 min read