In general, there are two ways to handle exceptions in Java.
- Add throws declaration in method signature
- 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?