为什么下面的java语句可以编译成功?
我想知道为什么有一个空的 try 块然后捕获特定的异常是有意义的?有什么想法吗?
try {
} catch (Exception e) {
// do nothing
}
I wonder why it makes sense to have an empty try block followed by catching specific exception? Any thoughts?
try {
} catch (Exception e) {
// do nothing
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这个想法是,任何代码都可以抛出未经检查的异常,因此,如果您捕获可以捕获未经检查的异常的内容,编译器不会检查
try< 中的代码是否/code> 块可以抛出任何东西。在 try 块中确实没有代码的特殊情况下,这是不合适的 - 但它使语言更简单,并且这只是我不希望显示的完全伪造代码中的问题在任何真实的代码库中。我想也有类似的情况,您只使用基元等进行操作,但这确实是一种边缘情况。大多数 try 块将包含理论上可能引发未经检查的异常的代码。
如果您尝试捕获未在
try
块中抛出的已检查异常类型,那么编译器会抱怨。The idea is that unchecked exceptions can be thrown by any code, so if you're catching something which can catch an unchecked exception, the compiler doesn't check whether the code in the
try
block can throw anything. In the special case where there really is no code in the try block, this is inappropriate - but it keeps the language simpler, and it's only a problem in completely bogus code which I wouldn't expect to show up in any real codebase. I guess there are similar situations where you're only doing things with primitives etc, but it really is an edge case. Most try blocks will contain code which could theoreically throw an unchecked exception.If you try to catch a checked exception type which isn't thrown in the
try
block, then the compiler will complain.运行时异常未经类型检查,可能会意外抛出
runtime exceptions are not type-checked and can be unpredictably thrown
并非所有编译的内容都应该“有意义”,只要您的代码不包含语法和语义错误,它就会编译并且很可能甚至运行。
主要思想是代码的每个部分都可能引发异常。
Try Catch
块不会给编译后的代码增加额外的开销,因此即使对于任何代码使用它们也没有问题。Not everything that compiles should "make sense", as long as your code does not contain syntax and semantic errors it will compile and most likely even run.
The main idea is that every part of your code can potentially throw an exception.
Try Catch
blocks do not add an additional overhead to your compiled code and thus there is no problem using them even for any code.