1

I have a simple Spring Boot MVC application, in which I would like to throw exceptions from the service layer. I handle those exceptions in the controller with a series of @ExceptionHandler annotated methods.

I do not understand why some of the exceptions do not need to be declared as thrown while some do. For instance, if I simply throw a

java.sql.SQLIntegrityConstraintViolationException

the compiler complains with:

java: unreported exception java.sql.SQLIntegrityConstraintViolationException; must be caught or declared to be thrown

whereas if I throw a

org.springframework.dao.DataIntegrityViolationException

I neither need to declare it to be thrown, nor to catch it in the controller. It simply gets taken care of by my ExceptionHandler.

What's the difference? And better yet, where may I find documentation on this?

Bill T
  • 93
  • 8

1 Answers1

3

This has nothing to do with Spring, it is core Java. Java has checked and unchecked exceptions. Checked need to be checked, these exceptions are checked at compile time. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using throws keyword. On other side you have unchecked exceptions - either Error or RuntimeException subclass - for these exceptions you dont have to declare throws I believe this question is duplicate to many other questions :) Check this Checked vs Unchecked exception

Michal Drozd
  • 1,311
  • 5
  • 13
  • 26