Table of contents
1.
Introduction
2.
Java Built In Exceptions
3.
Compile-time exceptions (Checked Exceptions)
3.1.
1. Checked Exceptions
3.2.
2. Unchecked Exceptions
4.
Java Exceptions that are User-Defined
4.1.
What is the Way to Develop a Custom Exception?
4.2.
Example: Age Validation Exception
5.
Situations when to use Custom Exceptions?
5.1.
Example 2: Unchecked custom exception
6.
Check and Uncheck Exceptions Difference
7.
Frequently Asked Questions
7.1.
What will occur when I do not handle a checked exception?
7.2.
Is it possible to declare my custom exception unchecked?
7.3.
What is the advantage of checking exceptions and unchecked exceptions in Java?
8.
Conclusion
Last Updated: Jun 22, 2025
Medium

Types of Exception in Java

Author Pallavi singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Exceptions are errors that occur in Java to interrupt the normal process of a program. They are triggered when an error happens at the time of execution, such as, when the user is performing a mathematical operation by dividing a number by zero or making an attempt to open a file that does not exist in the system. There is a mechanism in Java to deal with such exceptions and the program does not crash in a sudden way. 

Types of Exception in Java

The various types of exceptions in Java are what we will look at in this article and they include built-in exception which is the Java exceptions and user-defined exception which are exceptions that we ourselves can create. As well, we will also cover some of the major differences between checked & unchecked exceptions.

Java Built In Exceptions

Java has a good number of predefined exceptions that deal with frequent errors during a program. These exceptions belong to the standard library of Java, therefore, we do not necessarily have to declare them. They assist us in finding where we have something wrong in our code.

Built-in exceptions in Java are divided into two main types:

  • Checked Exceptions (Compile-time exceptions)
     
  • Unchecked Exceptions (Runtime exceptions)

Compile-time exceptions (Checked Exceptions)

Checked exceptions are checked by the compiler at compile time. If a method throws a checked exception, we must handle it using try-catch or declare it using throws.


Let us see them one by one with examples.

1. Checked Exceptions

Compile time checks, checked exceptions are the exceptions checked by the compiler at compile time. In case an approach throws a checked exception, we have to deal with it with the aid of a try-catch or state throws.

As an example, FileNotFoundException (When attempting to read a file that is not there)

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;


public class CheckedExceptionExample {
    public static void main(String[] args) {
        try {
            File file = new File("nonexistent.txt");
            Scanner scanner = new Scanner(file); // This line throws FileNotFoundException
            System.out.println("File read successfully.");
        } catch (FileNotFoundException e) {
            System.out.println("Error: File not found.");
        }
    }
}
You can also try this code with Online Java Compiler
Run Code


Output:

Error: File not found.


Under this code:

  • We have to deal with FileNotFoundException on behalf of the compiler.
     
  • Without using try-catch or throws, we can not compile the code.

2. Unchecked Exceptions

Unchecked exceptions do not check at a compile time. They arise as a result of bug errors in the code.


Example: ArithmeticException (Dividing by zero)

public class UncheckedExceptionExample {
    public static void main(String[] args) {
        int a = 10;
        int b = 0;
        System.out.println(a / b); // This throws ArithmeticException
    }
}
You can also try this code with Online Java Compiler
Run Code


Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero


In the present code:

  • The compiler does not bother us to cope with ArithmeticException.
     
  • All the programs are compiled but they crash up at runtime.

Java Exceptions that are User-Defined

There are situations when the built-in exception of Java is not satisfactory to our demands. Most of the time in real project we tend to create our own exceptions in dealing with certain errors. These are referred to as user-defined exceptions.

What is the Way to Develop a Custom Exception?

  • Extend Exception (checked exceptions)
     
  • Should be managed via try catch or throws.
     
  • Subclass RuntimeException (in case of unchecked exceptions)
     
  • Nor enforced treatment by the compiler.

Example: Age Validation Exception

Suppose we are creating a very simple voting system and allowing only people of age 18 years. We will design a special exception InvalidAgeException.

Step 1: Define Custom Exception

// Custom checked exception
class InvalidAgeException extends Exception {
    public InvalidAgeException(String message) {
        super(message); // Pass error message to parent class
    }
}
You can also try this code with Online Java Compiler
Run Code


Step 2: Make use of the Exception in Code

public class VotingSystem {
    public static void checkAge(int age) throws InvalidAgeException {
        if (age < 18) {
            throw new InvalidAgeException("Age must be 18 or above to vote.");
        } else {
            System.out.println("You are eligible to vote!");
        }
    }


    public static void main(String[] args) {
        try {
            checkAge(16); // This will throw InvalidAgeException
        } catch (InvalidAgeException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}
You can also try this code with Online Java Compiler
Run Code


Output:

Error: Age must be 18 or above to vote.


Important Notes to remember:

  • extends Exception -> Makes it a checked exception ( retrievable ).
     
  • throw new InvalidAgeException() -> Invokes the exception.
     
  • throws in method -> Annotation Declares that this method throws this exception.

Situations when to use Custom Exceptions?

  • Business rule checks (e.g. invalid age, inadequate balance).
     
  • Making decision errors more specific (better debugging).
     
  • It makes developers deal with some errors (checked exceptions).

Example 2: Unchecked custom exception

When we extend RuntimeException it will become unchecked exception.

// Custom unchecked exception
class InsufficientFundsException extends RuntimeException {
    public InsufficientFundsException(String message) {
        super(message);
    }
}


public class BankAccount {
    public static void withdraw(double balance, double amount) {
        if (amount > balance) {
            throw new InsufficientFundsException("Not enough money in account!");
        }
        System.out.println("Withdrawal successful.");
    }


    public static void main(String[] args) {
        withdraw(1000, 1500); // Throws InsufficientFundsException
    }
}
You can also try this code with Online Java Compiler
Run Code

Output:

Exception in thread "main" InsufficientFundsException: Not enough money in account!


Note:

  • No exception handling is required (unchecked exception).
     
  • Unless dealt with, it causes program crash.

Check and Uncheck Exceptions Difference

AspectChecked ExceptionUnchecked Exception
DefinitionCompile-time checked exceptions that must be either handled or declared in the method signature.Exceptions not checked at compile time; they occur at runtime.
Inheritance HierarchySubclasses of the Exception class but not of RuntimeException.Subclasses of RuntimeException, which itself extends Exception.
Compile-time HandlingMust be handled using try-catch blocks or declared using the throws keyword.Not mandatory to handle; compiler does not force exception handling.
Recovery PossibilityGenerally recoverable; program can continue running normally once handled.Usually non-recoverable; indicate bugs or logical errors in the code.
They Happen WhenCaused by external factors like missing files, network issues, or database connection failures.Caused by programming mistakes like null references, index out-of-bounds, or division by zero.
Performance ImpactHave minimal performance impact since they are anticipated and properly handled.May significantly impact performance if they occur frequently at runtime.
ExamplesIOException, SQLException, ClassNotFoundException, FileNotFoundException, InterruptedException.NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException, IllegalArgumentException, NumberFormatException.
Code ReadabilityCan make code verbose due to mandatory try-catch blocks, but improve documentation and error awareness.Keep code cleaner and simpler as handling them is optional.
Debugging DifficultyEasier to debug due to predictable nature and informative error messages.Harder to debug as they are often unexpected and may not have universal error handling.
Application StabilityEnhances application stability by enforcing proper error handling and recovery.Can reduce application stability if not handled properly; may cause the application to crash.

Frequently Asked Questions

What will occur when I do not handle a checked exception?

Unless you deal with a checked exception (with either try-catch or throws), your program will fail to compile. Java compiler makes you handle the exceptions which are checked in order to avoid possible run time failures.

Is it possible to declare my custom exception unchecked?

Yes, by deriving RuntimeException, and not Exception. This causes your exception to be an unchecked exception, i.e. not in any way enforced to be handled by the compiler. Application of it should be when the exception is not a failure by the external operation but the programmer instead.

What is the advantage of checking exceptions and unchecked exceptions in Java?

Check exceptions will make sure vital faults (such as lacking files) are dealt with. Uncaught exceptions are so that programming errors (such as null pointer) can be handled, but doing so forcedly may unnecessarily complicate code. The difference assists in creating cleaner and safer programs.

Conclusion

In this article we came to know about the exceptions in Java. We have seen that Java offers some exception classes such as NullPointerException or FileNotFoundException used to manage the simple mistakes. Another topic that we covered was how we can write our own custom exceptions when we want to deal with a particular type of exception.The major distinction between checked and unchecked exceptions is that when we have checked exceptions they have to be dealt with, whereas when we have unchecked exceptions, we do not explicitly need to deal with exceptions. The presence of checked exceptions allows excluding errors caused by external factors, whereas unchecked exceptions are most often related to code bug

Live masterclass