“为什么运行时异常不可恢复?” [英] "why the runtime exception is un-recoverable?"

查看:174
本文介绍了“为什么运行时异常不可恢复?”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java文档中,我看到了定义



如果可以合理地期望客户端从异常中恢复,请将其设置为已检查的异常。如果客户端无法采取任何措施来从异常中恢复,请使其成为未经检查的异常





全文讨论了我们处理异常的不同方式。
https://vanilla-java.github .io / 2016/06/21 / Reviewing-Exception-Handling.html


In the Java documentation, I saw the definition

"If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception"

Unchecked Exceptions — The Controversy

I don't understand clearly the concept "recover from", what does it means?

And, based on this definition, why NumberFormatException cannot recover? I think when this exception occurs, we can ask the user provide the other valid string to continue the program. Is that correct?

解决方案

If an error occurs the developer cannot reasonably recover from it should be an Error e.g. VerifyError or NoMuchMethodError. If a condition occurs I believe should be impossible, I use AssertionError

If an error occurs which the developer might be able to recover from, though most developers are unlikely to know how to deal the exception, use a RuntimeException as this doesn't force the developer to write handling code.

If an error is being passed to the caller to deal with, even if most developers don't know how to recover from exceptions, and even if they did, might find it hard to recover from that exception, a checked exception can be used.

You can also create a Throwable or a direct sub-class which is also checked, however I only use this as a simple way to print a stack trace i.e. make it clear it's not really an error. I suggest avoiding ever throwing such as Throwable as it is confusing and very unlikely to be handled correctly.

In our code base, we might say we use Exception effectively and in many cases write both the caller and callee which is be best chance to be able to pass exceptions in a useful manner. Never the less, recovering via a fallback accounts for only 19% of our catch cases, and a "signal" accounts of 6% of cases (A "Signal" is passing a checked exception from deep in the call stack on rare occasions)

In summary we only manage to handle and recover from about 25% of exceptions/errors in the manner I believe checked exceptions are intended. I think it's a valuable 25%, but I would be happier if it was higher.

For the full post discussing the different ways we handle exceptions. https://vanilla-java.github.io/2016/06/21/Reviewing-Exception-Handling.html

这篇关于“为什么运行时异常不可恢复?”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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