Java - Types of Exceptions

Java - Types of Exceptions | Detailed Notes

Types of Exceptions in Java

Java Exception Handling is one of the most important concepts in the Java programming language. When a program encounters an unexpected event or error during execution, Java creates an exception object. This exception represents a problem, and the normal flow of the program is disrupted. Java provides a strong and well-structured mechanism for identifying, handling, and recovering from runtime errors through its exception-handling framework. Understanding the various types of exceptions in Java is essential for writing robust, secure, and error-free applications. This document explains every major type of exception in Java in depth, with code examples, outputs, and proper HTML formatting.

Introduction to Exceptions in Java

An exception in Java is an event that occurs during program execution and disrupts the normal flow of the application. Java categorizes exceptions into several types based on the nature of the error, when it occurs, and whether it must be handled during compilation. Java exceptions can be broadly classified as:

  • Checked Exceptions
  • Unchecked Exceptions (Runtime Exceptions)
  • Errors

Java uses a class hierarchy rooted at the Throwable class, under which Exception and Error are the two main branches. In this document, we explain each type with detailed notes, examples, and outputs. These notes are written in an SEO-friendly way, including important keywords: Java Exception Handling, Java RuntimeException, Checked Exceptions in Java, Unchecked Exceptions in Java, Java Errors, Exception hierarchy, and example programs.

Types of Exceptions in Java

1. Checked Exceptions in Java

Checked exceptions are the exceptions that the Java compiler forces the programmer to handle explicitly. These exceptions represent conditions that a well-written application should anticipate and recover from. They occur during compile time, meaning if they are not handled using try-catch or declared using throws, the program will not compile. Examples include IOException, SQLException, FileNotFoundException, ClassNotFoundException, and more. These exceptions usually relate to external resources such as files, databases, or network operations. Because they deal with external factors, there is a significant chance of failure, making proper handling necessary. Checked exceptions help developers write reliable programs by ensuring that exceptional conditions are properly addressed.

Example: FileNotFoundException (Checked Exception)


import java.io.*;

public class CheckedExample {
    public static void main(String[] args) {
        try {
            FileReader fr = new FileReader("testfile.txt");
            System.out.println("File opened successfully.");
        } catch (FileNotFoundException e) {
            System.out.println("Exception: File not found!");
        }
    }
}
Output:

Exception: File not found!

This example shows how a checked exception must be handled. Since the compiler knows that FileReader may throw FileNotFoundException, it forces the programmer to write a try-catch block. This ensures that errors related to missing files do not crash the application unexpectedly. Checked exceptions improve program stability by making developers acknowledge potential risks in advance.

2. Unchecked Exceptions (Runtime Exceptions)

Unchecked exceptions are exceptions that occur during runtime. The compiler does not require the programmer to handle or declare them. These exceptions usually occur because of mistakes in code logic, such as invalid operations or accessing non-existing array elements. They belong to the RuntimeException class and commonly indicate programming errors. Examples include ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, NumberFormatException, and IllegalArgumentException. Because unchecked exceptions occur due to logical issues, they should be prevented through proper validation instead of try-catch blocks. Runtime exceptions are highly common, and understanding them deeply enables developers to debug effectively and write safer code.

Example: ArithmeticException (Unchecked Exception)


public class UncheckedExample {
    public static void main(String[] args) {
        int a = 10;
        int b = 0;

        try {
            int result = a / b;
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Exception: Cannot divide by zero!");
        }
    }
}
Output:

Exception: Cannot divide by zero!

In this program, dividing a number by zero produces an ArithmeticException, which is a type of RuntimeException. Java does not require handling it during compile time. Unchecked exceptions are often solved by fixing the logic instead of adding try-catch everywhere. However, they can be caught when necessary to prevent application crashes.

3. Errors in Java

Errors in Java are serious issues that occur in the JVM environment. They are not meant to be handled by developers in most situations. Errors represent failures in system-level operations that applications cannot typically recover from. Common examples include OutOfMemoryError, StackOverflowError, VirtualMachineError, and AssertionError. Errors belong to a separate branch under the Throwable class and do not extend Exception. Because errors occur due to resource depletion or JVM breakdown, adding try-catch blocks is not useful. Instead, developers must avoid writing code that can cause resource exhaustion. Understanding errors is essential for debugging large systems and optimizing memory usage.

Example: OutOfMemoryError


public class ErrorExample {
    public static void main(String[] args) {
        try {
            int[] arr = new int[1000000000];
        } catch (Error e) {
            System.out.println("Error caught: " + e);
        }
    }
}
Output:

Error caught: java.lang.OutOfMemoryError: Java heap space

Although errors generally should not be handled, the example demonstrates that they can be caught. However, catching errors is not the recommended approach, as doing so does not solve the root issue. Errors indicate that the JVM cannot continue execution normally.

Important Subtypes of Java Exceptions

4. IOException (Checked Exception)

IOException is one of the most frequently encountered checked exceptions in Java. It occurs when an input or output operation fails or is interrupted unexpectedly. This includes file reading, writing, networking, and communication errors. IOException forces developers to handle failures related to external devices or resources. Understanding IOException is essential when working with Java File Handling, BufferedReader, InputStream, OutputStream, and other I/O APIs. Because I/O operations depend on hardware and external systems, errors are common, making this exception a fundamental part of robust programming.

Example: IOException


import java.io.*;

public class IOExceptionExample {
    public static void main(String[] args) {
        try {
            BufferedReader br = new BufferedReader(new FileReader("data.txt"));
            System.out.println(br.readLine());
        } catch (IOException e) {
            System.out.println("IOException occurred: " + e.getMessage());
        }
    }
}
Output:

IOException occurred: data.txt (No such file or directory)

IOException helps developers gracefully handle cases where a file may be missing or unreadable. It ensures that the program does not crash abruptly due to issues outside the program’s control.

5. NullPointerException (Unchecked Exception)

NullPointerException is one of the most commonly occurring runtime exceptions in Java. It occurs when a program tries to use an object reference that has a null value. Since null indicates the absence of an object, calling a method or accessing a variable through null causes this exception. NullPointerException often comes from poor initialization or assumptions about object state. Avoiding it requires proper null checks, Optional usage, or defensive programming techniques. Understanding NPE is important for debugging because it is one of the top causes of runtime failures in Java applications.

Example: NullPointerException


public class NullPointerExample {
    public static void main(String[] args) {
        String s = null;

        try {
            System.out.println(s.length());
        } catch (NullPointerException e) {
            System.out.println("NullPointerException occurred!");
        }
    }
}
Output:

NullPointerException occurred!

This example shows how a null reference can cause errors at runtime. Preventing NullPointerException through validation is important for stable and reliable Java applications.

6. ArrayIndexOutOfBoundsException (Unchecked Exception)

This exception occurs when a program attempts to access an array index that does not exist. Java arrays have fixed sizes, and accessing a negative index or an index equal to or greater than the array length causes this exception. This runtime exception commonly occurs in loops and array manipulation. Understanding it is essential for writing safe code that processes arrays, lists, and data structures. Developers prevent this exception by performing boundary checks before accessing array elements.

Example: ArrayIndexOutOfBoundsException


public class ArrayIndexExample {
    public static void main(String[] args) {
        int[] arr = {10, 20, 30};

        try {
            System.out.println(arr[5]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array index is out of bounds!");
        }
    }
}
Output:

Array index is out of bounds!

This example demonstrates how invalid indices can lead to runtime exceptions. Proper validation ensures safer array handling.

7. NumberFormatException (Unchecked Exception)

NumberFormatException occurs when Java attempts to convert a string into a number, but the string does not contain a valid numeric format. This happens frequently when parsing user input, reading data from files, or converting values received from APIs. Because user input is unpredictable, validations must be performed before parsing. NumberFormatException is common in data validation and input processing applications, making it important to understand for real-world programming.

Example: NumberFormatException


public class NumberFormatExample {
    public static void main(String[] args) {
        String value = "abc123";

        try {
            int number = Integer.parseInt(value);
            System.out.println("Converted number: " + number);
        } catch (NumberFormatException e) {
            System.out.println("Invalid number format!");
        }
    }
}
Output:

Invalid number format!

This example shows how invalid numeric input leads to a NumberFormatException. Proper validation prevents errors during parsing.


Java provides a powerful and flexible exception-handling mechanism that helps developers identify, catch, manage, and recover from unexpected runtime conditions. Understanding the various types of exceptionsβ€”Checked Exceptions, Unchecked Exceptions, and Errorsβ€”is essential to writing clean, stable, and maintainable software. Checked exceptions ensure compile-time safety by forcing developers to anticipate and handle failures. Unchecked exceptions help identify logic errors that require code correction. Errors warn developers of serious system failures that cannot be recovered easily. By mastering Java exception types and applying best practices, programmers can develop robust Java applications that handle different error conditions gracefully and efficiently.

logo

Java

Beginner 5 Hours
Java - Types of Exceptions | Detailed Notes

Types of Exceptions in Java

Java Exception Handling is one of the most important concepts in the Java programming language. When a program encounters an unexpected event or error during execution, Java creates an exception object. This exception represents a problem, and the normal flow of the program is disrupted. Java provides a strong and well-structured mechanism for identifying, handling, and recovering from runtime errors through its exception-handling framework. Understanding the various types of exceptions in Java is essential for writing robust, secure, and error-free applications. This document explains every major type of exception in Java in depth, with code examples, outputs, and proper HTML formatting.

Introduction to Exceptions in Java

An exception in Java is an event that occurs during program execution and disrupts the normal flow of the application. Java categorizes exceptions into several types based on the nature of the error, when it occurs, and whether it must be handled during compilation. Java exceptions can be broadly classified as:

  • Checked Exceptions
  • Unchecked Exceptions (Runtime Exceptions)
  • Errors

Java uses a class hierarchy rooted at the Throwable class, under which Exception and Error are the two main branches. In this document, we explain each type with detailed notes, examples, and outputs. These notes are written in an SEO-friendly way, including important keywords: Java Exception Handling, Java RuntimeException, Checked Exceptions in Java, Unchecked Exceptions in Java, Java Errors, Exception hierarchy, and example programs.

Types of Exceptions in Java

1. Checked Exceptions in Java

Checked exceptions are the exceptions that the Java compiler forces the programmer to handle explicitly. These exceptions represent conditions that a well-written application should anticipate and recover from. They occur during compile time, meaning if they are not handled using try-catch or declared using throws, the program will not compile. Examples include IOException, SQLException, FileNotFoundException, ClassNotFoundException, and more. These exceptions usually relate to external resources such as files, databases, or network operations. Because they deal with external factors, there is a significant chance of failure, making proper handling necessary. Checked exceptions help developers write reliable programs by ensuring that exceptional conditions are properly addressed.

Example: FileNotFoundException (Checked Exception)

import java.io.*; public class CheckedExample { public static void main(String[] args) { try { FileReader fr = new FileReader("testfile.txt"); System.out.println("File opened successfully."); } catch (FileNotFoundException e) { System.out.println("Exception: File not found!"); } } }
Output:
Exception: File not found!

This example shows how a checked exception must be handled. Since the compiler knows that FileReader may throw FileNotFoundException, it forces the programmer to write a try-catch block. This ensures that errors related to missing files do not crash the application unexpectedly. Checked exceptions improve program stability by making developers acknowledge potential risks in advance.

2. Unchecked Exceptions (Runtime Exceptions)

Unchecked exceptions are exceptions that occur during runtime. The compiler does not require the programmer to handle or declare them. These exceptions usually occur because of mistakes in code logic, such as invalid operations or accessing non-existing array elements. They belong to the RuntimeException class and commonly indicate programming errors. Examples include ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, NumberFormatException, and IllegalArgumentException. Because unchecked exceptions occur due to logical issues, they should be prevented through proper validation instead of try-catch blocks. Runtime exceptions are highly common, and understanding them deeply enables developers to debug effectively and write safer code.

Example: ArithmeticException (Unchecked Exception)

public class UncheckedExample { public static void main(String[] args) { int a = 10; int b = 0; try { int result = a / b; System.out.println("Result: " + result); } catch (ArithmeticException e) { System.out.println("Exception: Cannot divide by zero!"); } } }
Output:
Exception: Cannot divide by zero!

In this program, dividing a number by zero produces an ArithmeticException, which is a type of RuntimeException. Java does not require handling it during compile time. Unchecked exceptions are often solved by fixing the logic instead of adding try-catch everywhere. However, they can be caught when necessary to prevent application crashes.

3. Errors in Java

Errors in Java are serious issues that occur in the JVM environment. They are not meant to be handled by developers in most situations. Errors represent failures in system-level operations that applications cannot typically recover from. Common examples include OutOfMemoryError, StackOverflowError, VirtualMachineError, and AssertionError. Errors belong to a separate branch under the Throwable class and do not extend Exception. Because errors occur due to resource depletion or JVM breakdown, adding try-catch blocks is not useful. Instead, developers must avoid writing code that can cause resource exhaustion. Understanding errors is essential for debugging large systems and optimizing memory usage.

Example: OutOfMemoryError

public class ErrorExample { public static void main(String[] args) { try { int[] arr = new int[1000000000]; } catch (Error e) { System.out.println("Error caught: " + e); } } }
Output:
Error caught: java.lang.OutOfMemoryError: Java heap space

Although errors generally should not be handled, the example demonstrates that they can be caught. However, catching errors is not the recommended approach, as doing so does not solve the root issue. Errors indicate that the JVM cannot continue execution normally.

Important Subtypes of Java Exceptions

4. IOException (Checked Exception)

IOException is one of the most frequently encountered checked exceptions in Java. It occurs when an input or output operation fails or is interrupted unexpectedly. This includes file reading, writing, networking, and communication errors. IOException forces developers to handle failures related to external devices or resources. Understanding IOException is essential when working with Java File Handling, BufferedReader, InputStream, OutputStream, and other I/O APIs. Because I/O operations depend on hardware and external systems, errors are common, making this exception a fundamental part of robust programming.

Example: IOException

import java.io.*; public class IOExceptionExample { public static void main(String[] args) { try { BufferedReader br = new BufferedReader(new FileReader("data.txt")); System.out.println(br.readLine()); } catch (IOException e) { System.out.println("IOException occurred: " + e.getMessage()); } } }
Output:
IOException occurred: data.txt (No such file or directory)

IOException helps developers gracefully handle cases where a file may be missing or unreadable. It ensures that the program does not crash abruptly due to issues outside the program’s control.

5. NullPointerException (Unchecked Exception)

NullPointerException is one of the most commonly occurring runtime exceptions in Java. It occurs when a program tries to use an object reference that has a null value. Since null indicates the absence of an object, calling a method or accessing a variable through null causes this exception. NullPointerException often comes from poor initialization or assumptions about object state. Avoiding it requires proper null checks, Optional usage, or defensive programming techniques. Understanding NPE is important for debugging because it is one of the top causes of runtime failures in Java applications.

Example: NullPointerException

public class NullPointerExample { public static void main(String[] args) { String s = null; try { System.out.println(s.length()); } catch (NullPointerException e) { System.out.println("NullPointerException occurred!"); } } }
Output:
NullPointerException occurred!

This example shows how a null reference can cause errors at runtime. Preventing NullPointerException through validation is important for stable and reliable Java applications.

6. ArrayIndexOutOfBoundsException (Unchecked Exception)

This exception occurs when a program attempts to access an array index that does not exist. Java arrays have fixed sizes, and accessing a negative index or an index equal to or greater than the array length causes this exception. This runtime exception commonly occurs in loops and array manipulation. Understanding it is essential for writing safe code that processes arrays, lists, and data structures. Developers prevent this exception by performing boundary checks before accessing array elements.

Example: ArrayIndexOutOfBoundsException

public class ArrayIndexExample { public static void main(String[] args) { int[] arr = {10, 20, 30}; try { System.out.println(arr[5]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Array index is out of bounds!"); } } }
Output:
Array index is out of bounds!

This example demonstrates how invalid indices can lead to runtime exceptions. Proper validation ensures safer array handling.

7. NumberFormatException (Unchecked Exception)

NumberFormatException occurs when Java attempts to convert a string into a number, but the string does not contain a valid numeric format. This happens frequently when parsing user input, reading data from files, or converting values received from APIs. Because user input is unpredictable, validations must be performed before parsing. NumberFormatException is common in data validation and input processing applications, making it important to understand for real-world programming.

Example: NumberFormatException

public class NumberFormatExample { public static void main(String[] args) { String value = "abc123"; try { int number = Integer.parseInt(value); System.out.println("Converted number: " + number); } catch (NumberFormatException e) { System.out.println("Invalid number format!"); } } }
Output:
Invalid number format!

This example shows how invalid numeric input leads to a NumberFormatException. Proper validation prevents errors during parsing.


Java provides a powerful and flexible exception-handling mechanism that helps developers identify, catch, manage, and recover from unexpected runtime conditions. Understanding the various types of exceptions—Checked Exceptions, Unchecked Exceptions, and Errors—is essential to writing clean, stable, and maintainable software. Checked exceptions ensure compile-time safety by forcing developers to anticipate and handle failures. Unchecked exceptions help identify logic errors that require code correction. Errors warn developers of serious system failures that cannot be recovered easily. By mastering Java exception types and applying best practices, programmers can develop robust Java applications that handle different error conditions gracefully and efficiently.

Related Tutorials

Frequently Asked Questions for Java

Java is known for its key features such as object-oriented programming, platform independence, robust exception handling, multithreading capabilities, and automatic garbage collection.

The Java Development Kit (JDK) is a software development kit used to develop Java applications. The Java Runtime Environment (JRE) provides libraries and other resources to run Java applications, while the Java Virtual Machine (JVM) executes Java bytecode.

Java is a high-level, object-oriented programming language known for its platform independence. This means that Java programs can run on any device that has a Java Virtual Machine (JVM) installed, making it versatile across different operating systems.

Deadlock is a situation in multithreading where two or more threads are blocked forever, waiting for each other to release resources.

Functional programming in Java involves writing code using functions, immutability, and higher-order functions, often utilizing features introduced in Java 8.

A process is an independent program in execution, while a thread is a lightweight subprocess that shares resources with other threads within the same process.

The Comparable interface defines a natural ordering for objects, while the Comparator interface defines an external ordering.

The List interface allows duplicate elements and maintains the order of insertion, while the Set interface does not allow duplicates and does not guarantee any specific order.

String is immutable, meaning its value cannot be changed after creation. StringBuffer and StringBuilder are mutable, allowing modifications to their contents. The main difference between them is that StringBuffer is synchronized, making it thread-safe, while StringBuilder is not.

Checked exceptions are exceptions that must be either caught or declared in the method signature, while unchecked exceptions do not require explicit handling.

ArrayList is backed by a dynamic array, providing fast random access but slower insertions and deletions. LinkedList is backed by a doubly-linked list, offering faster insertions and deletions but slower random access.

Autoboxing is the automatic conversion between primitive types and their corresponding wrapper classes. For example, converting an int to Integer.

The 'synchronized' keyword in Java is used to control access to a method or block of code by multiple threads, ensuring that only one thread can execute it at a time.

Multithreading in Java allows concurrent execution of two or more threads, enabling efficient CPU utilization and improved application performance.

A HashMap is a collection class that implements the Map interface, storing key-value pairs. It allows null values and keys and provides constant-time performance for basic operations.

Java achieves platform independence by compiling source code into bytecode, which is executed by the JVM. This allows Java programs to run on any platform that has a compatible JVM.

The Serializable interface provides a default mechanism for serialization, while the Externalizable interface allows for custom serialization behavior.

The 'volatile' keyword in Java indicates that a variable's value will be modified by multiple threads, ensuring that the most up-to-date value is always visible.

Serialization is the process of converting an object into a byte stream, enabling it to be saved to a file or transmitted over a network.

The finalize() method is called by the garbage collector before an object is destroyed, allowing for cleanup operations.

The 'final' keyword in Java is used to define constants, prevent method overriding, and prevent inheritance of classes, ensuring that certain elements remain unchanged.

Garbage collection is the process by which the JVM automatically deletes objects that are no longer reachable, freeing up memory resources.

'throw' is used to explicitly throw an exception, while 'throws' is used in method declarations to specify that a method can throw one or more exceptions.

The 'super' keyword in Java refers to the immediate parent class and is used to access parent class methods, constructors, and variables.

The JVM is responsible for loading, verifying, and executing Java bytecode. It provides an abstraction between the compiled Java program and the underlying hardware, enabling platform independence.

line

Copyrights © 2024 letsupdateskills All rights reserved