英文:
Why do I NOT need to catch certain exceptions in a Spring Boot MVC application?
问题
我有一个简单的Spring Boot MVC应用程序,在其中我想从服务层引发异常。我使用一系列带有@ExceptionHandler注解的方法在控制器中处理这些异常。
我不明白为什么有些异常不需要声明为抛出异常,而有些则需要。例如,如果我只是抛出一个
java.sql.SQLIntegrityConstraintViolationException
编译器会报错:
java: 未报告的异常java.sql.SQLIntegrityConstraintViolationException;必须捕获或声明为已抛出
而如果我抛出一个
org.springframework.dao.DataIntegrityViolationException
我既不需要声明抛出,也不需要在控制器中捕获它。它会被我的ExceptionHandler处理。
这两者之间有什么区别?而更好的是,我可以在哪里找到相关文档?
英文:
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?
答案1
得分: 3
这与Spring无关,它是核心Java。
Java有已检查和未检查的异常。已检查的异常需要进行检查,这些异常在编译时进行检查。如果某个方法内的代码抛出已检查异常,那么该方法必须处理该异常,否则必须使用throws关键字指定异常。
另一方面,您有未检查的异常 - 可能是Error或RuntimeException的子类 - 对于这些异常,您不必声明throws
。
我认为这个问题是许多其他问题的重复
请查看此链接https://stackoverflow.com/questions/4639432/checked-vs-unchecked-exception
英文:
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 https://stackoverflow.com/questions/4639432/checked-vs-unchecked-exception
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论