Why doesn't a RuntimeException require explicit exception handling?

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

  • Add throws declaration to method signature
  • Surround with a try / catch block.

However, I noticed that some exceptions, especially those that inherit from RuntimeException , do not require such explicit exception handling.

For example, I created an example method, as shown below, and marked as β€œNot required” for those 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 shouldn't it be explicitly caught to compile a RuntimeException , whereas how do other Exceptions do?

+6
source share
2 answers

For Java, a RuntimeException is considered a system exception and, as a rule, is not recovered, so you do not need to add a throw declaration to this method or use a catch try block to handle it. However, an exception is considered an application exception; it can be repaired.

+1
source

"If the client can reasonably expect recovery from the exception, make it a checked exception. If the client cannot do anything to recover from the exception, make it an uncontrolled exception." http://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html

+1
source

All Articles