在Java中,正在使用throws Exception而不是抛出多个特定异常的好习惯? [英] In Java, is using throws Exception instead of throwing multiple specific exceptions good practice?

查看:70
本文介绍了在Java中,正在使用throws Exception而不是抛出多个特定异常的好习惯?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在浏览Spring MVC框架的同时,我注意到,除非我误解,否则开发者倾向于抛出异常,而不是抛出多个异常。



我意识到在核心这个问题是经检查和未经检查的例外辩论,避免宗教战争,使用throws泛型异常是个好习惯?

解决方案

对于诸如Spring MVC这样的图书馆来说,什么是有意义的,这个MVC需要足够开放才能适应各种不同的用例,在编写特定应用程序时,并不一定适合你。这是其中一种情况。



如果您是指类,例如 Controller 接口,作为一种方法签名如

  handleRequest(HttpServletRequest请求,HttpServletResponse响应)
throws异常

这可能是因为从调用您的Controller的Spring类的角度(例如 DispatcherServlet ),他们不在乎你的代码调用的是什么类型的异常 - 诸如 DispatcherServlet 的库代码只需要知道这个类可能会抛出异常在一般情况下可以处理异常。



换句话说, DispatcherServlet 不需要知道什么控制器可能会抛出异常的特定类型 - 它会将其中的任何一个视为错误。这就是为什么方法签名是 throws Exception



现在,API作者可以使签名使用自定义异常类型为 SpringMvcException ,但这只会产生强制您在 handleRequest 方法,简单地包装它们,这是繁琐的工作样板代码。所以,由于几乎所有与Spring的一切都是为了让它尽可能简单轻便,他们更容易指定接口方法只是抛出异常


While looking through the Spring MVC framework I noticed that, unless I misunderstand, its developers favor throws Exception instead of throwing multiple exceptions.

I realize that at the core of this question is the checked versus unchecked exceptions debate, avoiding that religious war, is it a good practice to use throws generic exception?

解决方案

What makes sense for a library such as Spring MVC, which needs to be open enough to fit all sorts of different use cases, does not necessarily make sense for you to follow when writing a specific application. This is one of those cases.

If you are referring to classes such as the Controller interface which as a method signature such as

handleRequest(HttpServletRequest request, HttpServletResponse response) 
   throws Exception

This is likely because, from the perspective of the Spring classes which call into your Controller (such as DispatcherServlet), they don't care what type of Exception your code calls - library code such as DispatcherServlet only needs to know that this class may throw an Exception and therefore is capable of handling Exception in the general case.

In other words, DispatcherServlet doesn't need to know what specific type(s) of Exception your Controller may throw - it's going to treat any of them as an "error". This is why the method signature is throws Exception.

Now, the API authors could have made the signature use a custom exception type as SpringMvcException, but that would only have the effect of forcing you to handle any checked exception types in your handleRequest method and simply wrap them, which is tedious make-work boilerplate code. So, since pretty much everything with Spring is designed to make it as easy and lightweight for you to integrate with as possible, it's easier for them to specify that the interface method merely throws Exception.

这篇关于在Java中,正在使用throws Exception而不是抛出多个特定异常的好习惯?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆