Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does RuntimeException not require an explicit exception handling?

In general, there are two ways to handle exceptions in Java.

  1. Add throws declaration in method signature
  2. Surround with try/catch block.

However, I've noticed that some exceptions, especially the ones that inherit from RuntimeException, do not require such explicit exception handling.

For example, I created a sample method as below and marked "Not required" for the ones that do not require explicit exception handling.

public void textException(){
    int i = (new Random()).nextInt(100);

    switch (i){
    case 1:
        throw new NullPointerException();   //Not required
    case 2:
        throw new NumberFormatException();  //Not required
    case 3:
        throw new RuntimeException();       //Not required
    case 4:         
        throw new ClassNotFoundException(); //Required
    case 5:
        throw new IOException();            //Required
    case 6:
        throw new Exception();              //Required
    default:
        return;
    }
}

I noticed that RuntimeException inherits from Exception.

Why is it that RuntimeException does not need to be explicitly caught to be compiled whereas other Exceptions do?

like image 669
wns349 Avatar asked Feb 21 '13 05:02

wns349


People also ask

Can runtime exceptions be handled?

Generally the point of a RuntimeException is that you can't handle it gracefully, and they are not expected to be thrown during normal execution of your program.

Why are runtime exceptions unchecked?

Run-time exception is called unchecked exception since it's not checked during compile time. Everything under throwable except ERROR and RuntimeException are checked exception. Adding Runtime exception in program will decrease the clarity of program.

Do runtime exceptions need to be declared?

Runtime exceptions:A method signature does not need to declare runtime exceptions. A caller to a method that throws a runtime exception is not forced to catch the runtime exception. Runtime exceptions extend from RuntimeException or Error.

Why we should not throw runtime exception?

A RuntimeException should be thrown in those two cases because it prevents the rest of the call stack from having to declare the exception. From the Javadocs: "RuntimeException and its subclasses are unchecked exceptions.


1 Answers

For Java, RuntimeException is considered to be system exception, generally, it's not recoverable, so you needn't add throws declaration on the method or use try catch block to handle it. However, Exception is considered to be application exception, it is recoverable.

like image 120
Liu Yi Avatar answered Sep 30 '22 19:09

Liu Yi