Java exception handling is sub divided in to Errors, checked exceptions and unchecked exceptions. This question is about exceptions.
Normal Java exception handling is to extend the Exception class for checked exceptions and handle those as you need by considering exception hierarchy.
E.g.:
public class ExceptionA extends Exception {}
public class RunClass {
public static void main() {
try {
RunClass runClass = new RunClass();
runClass.doSomething();
} catch(ExceptionA eA) {
// Do ExceptionA related resolutions.
} catch(Exception e) {
// Do Exception related resolutions.
}
}
public doSomething() throws ExceptionA {
throw new ExceptionA();
}
}
But I saw major Spring books and even on the Internet tutorials mentioned with Spring-boot and in the context of micro-services always extend from RuntimeException class even with the @ControllerAdvice.
This is clear violation of Java exception handling basics. But still there is an argument saying that, it is extended with RuntimeException because of this exception is handled by @ExceptionHandler method and it is generated and handled both in runtime.
Still, because of this extension from RuntimeException makes compile time exception handling trail not visible and makes hard to trace back how exception is thrown up. Due to these reasons, I still believe, follow the basic Java checked and unchecked exception handling concept still with @ExceptionHandler method.
E.g.:
public class ExceptionRA extends RuntimeException {}
@ContollerAdvice
public class ExceptionHandler {
@ExceptionHandler(ExceptionRA.class)
public String handleException (Exception exception, Model model) {
return "exception";
}
}
@Controller
public class RunClass {
@RequestMapping("/url1")
public doSomething() {
throw new ExceptionRA();
}
}
Should I follow the extending RuntimeException for all exception scenarios with @ExcpetionHadler or follow the basic Java checked and unchecked mechanism with @ExceptionHaldler? Ideas, suggestions and corrections are welcome.