抛出 RuntimeException 的方法是否应该在方法签名中指出它? [英] Should methods that throw RuntimeException indicate it in method signature?

查看:28
本文介绍了抛出 RuntimeException 的方法是否应该在方法签名中指出它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,框架/JDK中的许多方法可能会抛出

For example, many methods in frameworks/JDK might throw

java.lang.SecurityException 

但这并没有在方法签名中指明(因为这是通常为检查异常保留的做法).我想争辩说,在方法 sigs 中声明 RuntimeExceptions 有很多好处(例如类似于静态类型检查).我是喝醉了还是其他?

but this is not indicated in the method signature (since that is a practice normally reserved for checked exceptions). I want to argue that declaring RuntimeExceptions in method sigs has many benefits (akin to static type checking for example). Am I drunk or otherwise?

推荐答案

我不会在签名中声明未经检查的异常,因为它会误导该 API 的用户.是否必须显式处理异常已不再明显.

I would not declare an unchecked exception in the signature, since it is misleading to the user of that API. It is no longer obvious whether the exception has to be explicitly handled.

在 javadoc 中声明它是一种更好的方法,因为它允许某人在他们认为必要时处理它,但知道他们可以根据需要忽略它.这使得检查和未检查之间的区别变得清晰.

Declaring it in the javadoc is a better approach since it allows someone to handle it if they think it is necessary, but knowing they can ignore it if they want. This makes the separation between checked and unchecked clear.

这篇关于抛出 RuntimeException 的方法是否应该在方法签名中指出它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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