Exceptions in Java are events that occur during program execution and disrupt the normal flow of a program. Java provides many built-in exceptions to handle common runtime and compile-time errors. Developers can also create custom exceptions to handle application-specific error conditions.
- Exceptions help detect and handle errors gracefully.
- Java provides both built-in and user-defined exceptions.
- Proper exception handling improves program reliability and maintainability.

Built-in Exceptions
Built-in exceptions are predefined exception classes provided by Java's standard library to handle common runtime and compile-time errors. They help identify and manage abnormal situations such as invalid input, file errors, arithmetic errors, and null references. Java automatically throws these exceptions when such conditions occur.
- Built-in exceptions are predefined and available in Java libraries.
- They help handle common errors and prevent unexpected program termination.
Examples of Built-in Exception
1. ArithmeticException
ArithmeticException occurs when an illegal arithmetic operation is performed, such as division by zero.
- Commonly occurs during mathematical calculations.
- It is an unchecked exception.
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");
}
}
}
Output
Can't divide a number by 0
2. NullPointerException
NullPointerException occurs when a program tries to access a method or variable using a null reference.
- One of the most common runtime exceptions.
- Occurs when an object reference points to null.
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..
3. StringIndexOutOfBoundsException
StringIndexOutOfBoundsException occurs when an invalid index is used to access characters in a string.
- Happens when index is less than 0 or greater than string length.
- Thrown by String class methods.
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
4. FileNotFoundException
FileNotFoundException occurs when a specified file cannot be found or opened.
- Common in file handling operations.
- It is a checked exception.
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("E://file.txt");
FileReader fr = new FileReader(file);
} catch (FileNotFoundException e) {
System.out.println("File does not exist");
}
}
}
Output:
File does not exist5. NumberFormatException
NumberFormatException occurs when a string cannot be converted into a numeric value.
- Commonly occurs with parsing methods.
- It is an unchecked exception.
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
6. ArrayIndexOutOfBoundsException
ArrayIndexOutOfBoundsException occurs when an invalid array index is accessed.
- Index is either negative or exceeds array size.
- It is an unchecked exception.
class ArrayIndexOutOfBound_Demo
{
public static void main(String args[])
{
try{
int a[] = new int[5];
a[6] = 9; // accessing 7th element in an array of
// size 5
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println ("Array Index is Out Of Bounds");
}
}
}
Output
Array Index is Out Of Bounds
7. IOException
IOException occurs when an input/output operation fails during file or stream processing.
- Related to reading and writing data.
- It is a checked exception.
class IOException_Demo {
public static void main(String[] args)
{
// Create a new scanner with the specified String
// Object
Scanner scan = new Scanner("Hello Geek!");
// Print the line
System.out.println("" + scan.nextLine());
// Check if there is an IO exception
System.out.println("Exception Output: "
+ scan.ioException());
scan.close();
}
}
Output:
Hello Geek!
Exception Output: null
8. NoSuchMethodException
NoSuchMethodException occurs when a requested method does not exist.
- Common in Reflection API.
- It is a checked exception.
public class NoSuchElementException_Demo {
public static void main(String[] args)
{
Set exampleleSet = new HashSet();
Hashtable exampleTable = new Hashtable();
exampleleSet.iterator().next();
//accessing Set
exampleTable.elements().nextElement();
//accessing Hashtable
// This throws a NoSuchElementException as there are
// no elements in Set and HashTable and we are
// trying to access elements
}
}
9. IllegalArgumentException
IllegalArgumentException occurs when a method receives an invalid argument.
- Indicates inappropriate method parameters.
- It is an unchecked exception.
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
public static void print(int a)
{
if(a>=18){
System.out.println("Eligible for Voting");
}
else{
throw new IllegalArgumentException("Not Eligible for Voting");
}
}
public static void main(String[] args) {
GFG.print(14);
}
}
Output :
Exception in thread "main" java.lang.IllegalArgumentException: Not Eligible for Voting
at GFG.print(File.java:13)
at GFG.main(File.java:19)
10. IllegalStateException
IllegalStateException occurs when a method is invoked at an inappropriate time or state.
- Indicates the object is not in the required state.
- It is an unchecked exception.
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
public static void print(int a,int b)
{
System.out.println("Addition of Positive Integers :"+(a+b));
}
public static void main(String[] args) {
int n1=7;
int n2=-3;
if(n1>=0 && n2>=0)
{
GFG.print(n1,n2);
}
else
{
throw new IllegalStateException("Either one or two numbers are not Positive Integer");
}
}
}
Output :
Exception in thread "main" java.lang.IllegalStateException: Either one or two numbers are not Positive Integer
at GFG.main(File.java:20)
11. ClassNotFoundException
ClassNotFoundException occurs when the JVM cannot find a specified class at runtime.
- Common when loading classes dynamically.
- It is a checked exception.
public class ClassNotFoundException_Demo
{
public static void main(String[] args) {
try{
Class.forName("Class1"); // Class1 is not defined
}
catch(ClassNotFoundException e){
System.out.println(e);
System.out.println("Class Not Found...");
}
}
}
Output
java.lang.ClassNotFoundException: Class1 Class Not Found...
User-Defined Exceptions
User-defined exceptions are custom exceptions created by programmers to handle application-specific error conditions that are not covered by Java's built-in exceptions.
- Created by extending the Exception class.
- Used to represent custom business logic errors.
Syntax:
class MyException extends Exception {
MyException() { }
MyException(String message) {
super(message);
}
}
Throwing a User-Defined Exception:
MyException me = new MyException("Exception details");
throw me;
Example
class MyException extends Exception
{
//store account information
private static int accno[] = {1001, 1002, 1003, 1004};
private static String name[] =
{"Nish", "Shubh", "Sush", "Abhi", "Akash"};
private static double bal[] =
{10000.00, 12000.00, 5600.0, 999.00, 1100.55};
// default constructor
MyException() { }
// parameterized constructor
MyException(String str) { super(str); }
// write main()
public static void main(String[] args)
{
try {
// display the heading for the table
System.out.println("ACCNO" + "\t" + "CUSTOMER" +
"\t" + "BALANCE");
// display the actual account information
for (int i = 0; i < 5 ; i++)
{
System.out.println(accno[i] + "\t" + name[i] +
"\t" + bal[i]);
// display own exception if balance < 1000
if (bal[i] < 1000)
{
MyException me =
new MyException("Balance is less than 1000");
throw me;
}
}
} //end of try
catch (MyException e) {
e.printStackTrace();
}
}
}
Runtime Error
MyException: Balance is less than 1000
at MyException.main(fileProperty.java:36)
Output:
ACCNO CUSTOMER BALANCE
1001 Nish 10000.0
1002 Shubh 12000.0
1003 Sush 5600.0
1004 Abhi 999.0