Wednesday, July 12, 2023

Difference between RuntimeException and checked Exception in Java

RuntimeException vs Checked Exception in Java
Java Exceptions are divided into two categories RuntimeException also known as unchecked Exception and checked Exception. Main difference between RuntimeException and checked Exception is that It is mandatory to provide try-catch or try finally block to handle checked Exception and failure to do so will result in a compile-time error, while in the case of RuntimeException this is not mandatory. The difference between checked and unchecked exception is one of the a most popular question on Java interview for 2 to years experienced developer especially related to Exception concepts.


The answer to this question is rather similar as mentioned in previous lines and they are mostly asked along with other Java Exception interview questions like difference between throw and throws an Error vs Exception

Any Exception which is a subclass of RuntimeException are called unchecked and mandatory exception handling is no requirement for them.

Some of the most common Exception like NullPointerException, ArrayIndexOutOfBoundException are unchecked and they are descended from java.lang.RuntimeException. Popular example of checked Exceptions are ClassNotFoundException and IOException and that's the reason you need to provide a try catch finally block while performing file operations in Java as many of them throws IOException

Similarly many utilities of Reflection API throws java.lang.ClassNotFoundException. In this Java tutorial we will see some more difference between RuntimeException and checked Exception in Java.




Runtime Exception vs Checked Exception in Java

Apart from the fundamental difference between Runtime and checked exception, another burning question is while creating custom Exception should you make them unchecked by deriving from java.lang.RuntimeException or checked? well, this decision is purely yours though some thoughts are available in the Java community. I mostly see JDK when in doubt and try to follow practices available in JDK. 

If a method is likely to fail and the chances of failure are more than 50% it should throw Checked Exception to ensure alternate processing in case it failed. Another thought is that programming errors should be unchecked and derived from RuntimeException e.g. java.lang.NullPointerException

Here is a nice diagram which shows Exception and Error hierarchy which also clears out the difference between RuntimeException and checked Exception:

Difference between RuntimeException and checked Exception in Java



Checked Exception also enforces proper handling of the error condition, though it's theoretical in nature and many programs simply appease compiler by providing try catch block instead of correctly handling exceptions in the catch block. 

One of the disadvantage of checked exception over runtime exception is that it makes your code ugly by adding boilerplate code in form of try-catch-finally block. Though this issue is addressed to some extent by improved Exception handling in JDK 7 by introducing automatic resource management or ARM blocks and allowing to catch multiple Exception in same catch block.

RuntimeExcpetion vs Checked Exception in JavaThat's all on the difference between runtime exception and checked in Java. this question can also be asked as checked vs unchecked exception. Unchecked means compiler doesn't check and Checked means compiler checks for exception handling.


Other Java Interview questions you may like

8 comments:

  1. Haha! Bad, very bad answer. The try/catch is not mandatory at all. It is mandatory to do something with the checked exception: EITHER try/catch it OR declare it in throws clause.
    The same is true even for the main(String[]) methods. Period. Don't confuse people.

    ReplyDelete
    Replies
    1. Hello @Anonymous, can you point what is incorrect? I said, its mandatory to provide try-catch or try-finally or try-catch-finally block to handle the checked exception, ofcourse you can throw it if you want to using throws class, but if you want to handle, you must provide try-catch-finally block.

      Delete
  2. ya! for checked exception, either u can use try/catch or use 'throws' in the method signature to prevent compilation error.
    try-catch block is necessary to handle the runtime exceptions at runtime.

    ReplyDelete
    Replies
    1. Hello @Arun, yes, you are right. try catch block is necessary to handle both checked and runtime exception, but for checked its mandatory to handle if you are not throwing it, for runtime, its not mandatory.

      Delete
  3. Please answer the WHY of this:
    1]why try catch is necessary to handle checked exception
    2]why try catch is optional to handle runtime exception

    ReplyDelete
    Replies
    1. Hello Aamir, In Java, the try-catch mechanism is necessary to handle checked exceptions due to the compile-time nature of these exceptions. Checked exceptions, such as IOException or SQLException, are enforced by the compiler to be either caught using a try-catch block or explicitly declared in the method signature using the throws clause.

      This requirement ensures that developers acknowledge and address potential exceptional conditions, promoting robust error handling and preventing unhandled exceptions during runtime.

      By enforcing explicit handling or declaration, Java enhances the reliability and stability of programs, reducing the risk of unexpected failures due to unchecked exceptions.

      Delete
    2. And, regarding 2nd question, In Java, the use of try-catch is optional for handling runtime exceptions because runtime exceptions, including those derived from the RuntimeException class, are not checked at compile time.

      Unlike checked exceptions, which the compiler mandates to be caught or declared, runtime exceptions are unchecked and need not be explicitly handled. This design choice allows developers flexibility and encourages a balance between robust error handling and code conciseness.

      While it provides the freedom to handle runtime exceptions selectively, it also places the responsibility on developers to employ best practices and implement appropriate error-handling mechanisms where necessary.

      This approach aims to strike a balance between the need for robust software and the developer's autonomy in managing exceptions efficiently.

      I hope this clear your doubt, thanks

      Delete

Feel free to comment, ask questions if you have any doubt.