为了理解目的,我创建了以下代码。
在下面的代码中,try block 中有一个错误,因此它应该转到 catch block 并打印 15,因为finally block 总是被执行,我们也应该得到 20。 但在输出中我只得到 20 而不是 15。
请告知为什么会有这样的描述。我是Java初学者。 如果需要同时获得 15 和 20 作为输出,还可以在程序中进行任何必要的更改。
package javaapplication91;
public class NewClass
{
public static void main(String[] args)
{
NewClass n = new NewClass();
int z = n.m1();
System.out.println("z = " + z);
}
public int m1()
{
try
{
int a = 10/0;
System.out.println("Exception created");
return 10;
}
catch(ArithmeticException ae)
{
return 15;
}
finally
{
return 20;
}
}
}
最佳答案
如果方法声明返回值类型为 int
,则只能从方法返回一个值。
当你处理异常ArithmeticException
时,你尝试返回15,但你得到了20,因为finally
总是在try catch
的末尾阻止执行> block ,它将是最后一个返回语句。
您可以阅读终于
here (Java Tutorial)
如果你想返回两个值,你可以使用数组或列表,如下所示:
public List<Integer> m1() {
List<Integer> returnValues = new ArrayList<Integer>();
try {
int a = 10/0;
System.out.println("Exception created");
returnValues.add(10);
} catch(ArithmeticException ae) {
returnValues.add(15);
} finally {
returnValues.add(20);
return returnValues;
}
}
关于java - 异常处理中的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41504955/