Java Exceptions – Checked vs Unchecked

In this Java exceptions tutorial, learn what is an exception in Java. Learn what is the difference between a checked exception and an unchecked exception. We will also learn some Java exception handling best practices.

Table of Contents

1. What is an exception in Java?
2. Checked vs unchecked exceptions
3. Exception handling best practices

1. What is an exception in Java?

“An exception is an unexpected event that occurred during the execution of a program, and disrupts the normal flow of instructions.”

In Java, all errors and exceptions are of type with Throwable class. When an error occurs within a method, the method creates an object (or any subtype of Throwable) and hands it off to the runtime system. This object is called the exception object.

The exception object contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.

A few examples of an exception in the program execution can be:

  • User entered alphanumeric input and program excepts numeric input.
  • Program tries to read file but the file does not exist in specified location.
  • A network connection terminated while reading data from a webservice.
try {
    Integer.parseInt("six") ;
}
catch(NumberFormatException nfe) {
    //handle exception
}

1.1. How to handle an Exception

We have two choices when an exception object is created in our application.

  • Either we will handle it within method
  • Or we can pass it to the caller method to let it handle.

This is very important decision to be made while setting the responsibilities of a method. A method should clearly indicate that what all exceptions it will handle and which it will not. It is defined in the method declaration using the throws keyword.

To handle the exception, We must catch the exception in catch section of try-catch block.

try {
    //code
}
catch(Exception e) {
    //handle exception
}

If an exception is not handled in the application, then it will propagate to JVM and JVM usually terminates the program.

2. Checked Exception vs Unchecked Exception

2.1. Exception Hierarchy

In Java, exceptions are broadly categorized into two sections:

  • Checked exceptions
  • Unchecked exceptions

ExceptionHierarchy in Java

2.2. Checked Exceptions

Java checked exceptions are those exceptions, as the name suggests, which a method must handle in its body or throw to the caller method so the caller method can handle it.

Checked exceptions are checked by the Java compiler so they are called compile time exceptions.

Java compiler forces us to handle these exceptions in some manner in the application code. We must handle these exceptions at a suitable level inside the application so that we can inform the user about the failure and ask him to retry or come later.

Generally, checked exceptions denote error scenarios that are outside the immediate control of the program. These occur usually interacting with other systems/network resources e.g. database errors, network connection errors, missing files, etc.

Note that all checked exceptions are subclasses of Exception class. For example,

  • ClassNotFoundException
  • IOException
  • SQLException
2.2.1. Checked Exception Example

FileNotFoundException is a checked exception in Java. Anytime, we want to read a file from the filesystem, Java forces us to handle an error situation where the file may not be present in the place.

public static void main(String[] args) 
{
    FileReader file = new FileReader("somefile.txt");
}

In above case, you will get compile time error with message – Unhandled exception type FileNotFoundException.

To make the program able to compile, we must handle this error situation in the try-catch block. Below given code will compile absolutely fine.

public static void main(String[] args) 
{
    try 
    {
		FileReader file = new FileReader("somefile.txt");
	} 
    catch (FileNotFoundException e) 
    {
    	//Alternate logic
		e.printStackTrace();
	}
}

2.3. Unchecked Exception Example

Unchecked exceptions are not checked by the compiler. These are called runtime exceptions.

Unchecked exceptions will come into life and occur in the program, once any buggy code is executed.

In Java, a member method is not forced by the compiler to declare the unchecked exceptions into the method declaration. Generally, such methods almost always do not declare them.

Unchecked Exceptions are subclasses of RuntimeException class.

  • ArithmeticException
  • ArrayStoreException
  • ClassCastException
“The strange thing is that RuntimeException is itself subclass of Exception i.e. all unchecked exception classes should have been checked exceptions implicitly, BUT they are not.”
2.3.1. Unchecked Exception Example

The code in the given program does not give any compile time error. But when we run the example, it throws NullPointerException. NullPointerException is an unchecked exception in Java.

public static void main(String[] args) 
{
    try 
    {
		FileReader file = new FileReader("pom.xml");
		
		file = null;
		
		file.read();
	} 
    catch (IOException e) 
    {
    	//Alternate logic
		e.printStackTrace();
	}
}

Remember the biggest difference between checked and unchecked exceptions is that checked exceptions are forced by the compiler and used to indicate exceptional conditions that are out of the control of the program, while unchecked exceptions are occurred during runtime and used to indicate programming errors.

3. Java exception handling best practices

  1. Checked exceptions can be used when a method may fail to do what it must. For example, A method named prepareSystem() which pre-populate configuration files and do some configuration using them. It can declare throwing FileNotFoundException which implies that method uses configuration files from file system and they are missing.
  2. Checked exceptions ideally should never be used for programming errors, but absolutely should be used for resource errors and for flow control in such cases.
  3. Throw only those exceptions which a method can not handle by any means. The method should first try to handle it as soon as it encounters. Throw the exception only if it is not possible to handle it inside the method.
  4. A good way to define method signatures is to declare exceptions close to method name. If the method is named openFile(), then it is expected to throw FileNotFoundException?. If the method is named findProvider(), then it is expected to throw NoSuchProviderException.

    Also, these type of exceptions should be made checked exceptions as it forces the caller to deal with the problems that are inherent to the semantic of the methods.

  5. Rule is if a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.

    In reality, most applications will have to recover from pretty much all exceptions including NullPointerException, IllegalArgumentExceptions and many other unchecked exceptions. The action/transaction that failed will be aborted but the application has to stay alive and be ready to serve the next action/transaction.

    The only time it is normally legal to shut down an application is during startup. For example, if a configuration file is missing and the application cannot do anything sensible without it, then it is legal to shut down the application.

4. Conclusion

In this Java tutorial, we learned about Java exceptions. We learned the difference between checked vs unchecked exceptions in Java, along with how to handle unchecked exceptions, exception hierarchy in Java with examples.

Happy Learning !!

Read More:

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

20 thoughts on “Java Exceptions – Checked vs Unchecked”

  1. As i heard that checked exceptions should not consider at all. Most languages will not use them too. But one can always throw a subclass of Runtime Exception i.e, unchecked exception according to my thoughts checked exceptions are useful as they are used when someone wants to force the user of their API to think how to carry on the exceptional situation. And people hate checked exceptions because they are overused in the Java platform.

    The main difference with Checked and UnChecked Exception is that checked Exception requires mandatory try catch or try finally block but unchecked Exception don’t. Another difference between Checked and UnChecked Exception is in where to use them.

    Checked Exception should be used if you know how to recover from Exception while Unchecked Exception should be used for programming errors.

    And i have a question for you regarding this article, can you please clarify me. My question is that If you can handle checked exception, then why not each exception is checked exception? why java have a concept of unchecked exception? Thanks for your detailed blog…

    Reply
    • Because an unchecked exception cannot be detected at compilation time e.g if u try to access an index of array beyond range it can only be detected only when the program runs not before that.

      Reply
  2. The exceptions which are checked by compiler for smooth execution of the program at run time are called checked exception. keep blogging.

    Reply
  3. Hi Lokesh,

    Checked exceptions are the subclass of Exception and Unchecked exception are the subclass of RuntimeException(RuntimeException is a subclass of Exception again).

    Suppose you have two custom exception classes MyException1.java(This extends RuntimeException) and MyException2.java(Extends Exception class).

    Suppose a method in any class throws MyException1 exception. While calling this method in any other places,it is not mandatory to catch the exception.But if the method throws MyException2 exception you are forced to catch the exception.(Either surround with try/catch or throws the exception).

    My question is when your custom exception class extends RuntimeException why it is not treated as a checked exception,? even tough RuntimeException the Exception class?

    Regards
    Partha

    Reply
      • I already mentioned: “Here, the strange thing is that RuntimeException is itself subclass of Exception i.e. all Unchecked exception classes should have been checked exceptions implicitly, BUT they are not. I am confuse. Any thoughts??”

        I am really clueless about this design choice, JDK designers followed…

        Reply
        • As per my thought, it is just an indication to the JVM, so it works accordingly. from the Java DOC, RuntimeException is Unchecked and Exception is Checked. So when our exception class extends the RuntimeException , it will be treated as Unchecked exception by the JVM and Exception will be treated as Checked exception.

          Not sure about this but this is my thought.

          Reply
  4. Hi,
    Would like to know how compiler comes to know that a particular piece of code would result into a CheckedException. Meaning, if we use FILE IO or DB connection related utilities and don’t declare or handle them, then its a compile time error. In a way we can say that compiler is monitoring each and every line of code that we are introducing into the application but I am not sure how it understands and forces us to handle CheckedExceptions. Please suggest.

    Reply
  5. Hello Lokesh. Thanks for this post and very well explained. could you please tell me the difference between
    Throws and Throw ? as i am little but confusing about these two

    Reply
    • `throws` declares the exceptions the method throws, and is used in the method signature.

      `throw` is used to throw an exception

      “`
      void foo() throws Exception1 {

      throw new Exception1(“Something bad happened”);

      }
      “`

      Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.