- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有以下代码
public static void nocatch()
{
try
{
throw new Exception();
}
finally
{
}
}
这给出了错误
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type CustomException
我的问题是,为什么catch block 被设计为可选的,而没有办法避免没有catch?
<小时/>从finally()的角度来看,我明白
finally
应该至少有一个 try
block ,catch
是可选的。 finally block 的目的是确保无论是否抛出异常,内容都会得到清理。根据JLS
<小时/>A finally clause ensures that the finally block is executed after the try block and any catch block that might be executed, no matter how control leaves the try block or catch block.
编辑:
通过在finally block 中添加return,编译器不会给出错误WHY?!
public static void nocatch()
{
try
{
throw new Exception();
}
finally
{
return; //By adding this statement, the compiler error goes away! Please let me know why
}
}
最佳答案
My Question is why was it designed that the catch block is optional, when there is no way of getting around not having a catch?
是的,有:声明该方法抛出异常:
public static void nocatch() throws CustomException
{
try
{
throw new CustomException();
}
finally
{
}
}
不带
catch
的
try/finally
是为了确保清理所有需要清理的内容,即使您自己没有处理异常。 (请确保不允许从 finally
中抛出任何其他异常,否则您将隐藏主要异常。)
这是一个可以使用的示例( live copy ):
private static class CustomException extends Exception {
}
public static void main (String[] args) throws java.lang.Exception
{
try
{
System.out.println("Calling nocatch(false)");
nocatch(false);
}
catch (CustomException ce) {
System.out.println("Caught CustomException for false case");
}
try
{
System.out.println("Calling nocatch(true)");
nocatch(true);
}
catch (CustomException ce) {
System.out.println("Caught CustomException for true case");
}
}
public static void nocatch(boolean foo) throws CustomException
{
try
{
if (foo) {
System.out.println("Throwing");
throw new CustomException();
}
}
finally
{
System.out.println("In finally");
}
System.out.println("Reached outside the try/finally block");
}
输出:
Calling nocatch(false)In finallyReached outside the try/finally blockCalling nocatch(true)ThrowingIn finallyCaught CustomException for true case
As you can see, the finally
block's code runs regardless of whether an exception occurred, but the code after the try/finally
doesn't.
Re your follow-up asking why adding return
within the finally
makes the error go away:
try
{
throw new CustomException();
}
finally
{
return; // <=== Makes the compiler happy (but don't do it!)
}
有趣的边缘情况!这是因为 finally
block 中的代码始终运行,因此您将始终返回而不是抛出,从而隐藏发生的异常。例如,这是序列:
throw new CustomException()
抛出异常,将控制权转移到 finally
block
finally
block 中的代码从方法中发出正常返回
这隐藏了异常发生的事实;实际上,您已经通过finally
block “处理”了异常(但没有实际处理它)。一般来说,这不是一个好主意。使用catch
来处理异常,或者在方法上声明它们,以便调用代码可以处理它们。
关于java - 为什么 catch block 是可选的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28856947/
我正在尝试用 Swift 编写这段 JavaScript 代码:k_combinations 到目前为止,我在 Swift 中有这个: import Foundation import Cocoa e
我是一名优秀的程序员,十分优秀!