10

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?

2
  • 3
    Those are called Checked and Unchecked exceptions in Java. And these have been discussed many times in SO look into stackoverflow.com/questions/6115896/… Commented Feb 21, 2013 at 5:24
  • A method is not required to declare in its throws clause any subclasses of RuntimeException that might be thrown during the execution of the method but not caught. Commented Feb 21, 2013 at 5:25

2 Answers 2

3

"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." http://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.