Java抛出RuntimeException有什么好处
沿着方法签名声明 (Unchecked Exception) 抛出异常的好处是什么 b/c 它不会强制调用者保留在 try catch 块中。
public void testRuntimeEx()throws RuntimeException{
if(1==1){throw new RuntimeException()}
}
//Caller method
public void testCaller(){
// not necessery to handle even caller does not known which RuntimeException might be throws then what is the benefit throws clause with method signature
testRuntimeEx();
}
What is the benefit of declaring (Unchecked Exception)throws exception along method signature b/c it does not force caller to keep in try catch block.
public void testRuntimeEx()throws RuntimeException{
if(1==1){throw new RuntimeException()}
}
//Caller method
public void testCaller(){
// not necessery to handle even caller does not known which RuntimeException might be throws then what is the benefit throws clause with method signature
testRuntimeEx();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它仍然充当文档,特别是如果您不使用通用的 RuntimeException,而是使用更具体的内容,例如 IllegalArgumentException 或 UnsupportedOperationException 或 IndexOutOfBoundsException 并添加一些JavaDoc 关于何时会发生这种情况。
不过,在您的示例代码片段中,它毫无意义。
It still serves as documentation, especially if you do not use a generic RuntimeException, but something more specific like IllegalArgumentException or UnsupportedOperationException or IndexOutOfBoundsException and also add some JavaDoc as to when that would happen.
In your example code snippet, it is pretty meaningless, though.
对于使用此代码的开发人员来说,此声明是一个信号,它会抛出 RuntimeException。
但味道不太好闻。
您发布的 PS 代码将无法编译:
这不是正确的抛出。
This declaring is a signal for developer who uses this code, that it throws RuntimeException.
But it doesn't smell good.
P.S. Code you posted will not compile:
This is not correct throwing.
好处是通常调用者与异常没有任何关系。它捕获它,用其他异常包装并再次抛出。或者,使用
throws
关键字声明异常,并且如果出现异常,则对该类型变得透明。我想说,所描述的情况对于我们通常编写业务代码并有一个集中位置来处理所有异常的应用程序来说是典型的。对于 API 来说这是不正确的。例如,如果您正在使用实现 SSH 的库,您希望它在出现问题时抛出 IOException(甚至更专业的异常)。
The benefit is that typically caller does not have anything to do with the exception. It catches it, wraps with other exception and throws again. Or, alternatively, declares the exception using
throws
keyword and becomes transparent for this type if exception.I'd say that the described situation is typical for applications where we usually write business code and have one centralized place that handles all exceptions. It is not correct for APIs. For example if you are using library that implements SSH you are expecting it to throw
IOException
(or even more specialize exception) when something is going wrong.如果您抛出自定义未经检查的异常,它会变得更有意义,而不是捕获系统异常,并且未经检查的异常也不会强制捕获。
if you throw custom unchecked exception it becomes more meaningfull rather catching system exception and unchecked exception does not force to catch too.