最后添加return会隐藏异常 [英] Adding return in finally hides the exception

查看:60
本文介绍了最后添加return会隐藏异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码

public static void nocatch()
{
    try
    {
        throw new Exception();
    }
    finally
    {

    }
}

给出错误的地方

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
Unhandled exception type CustomException

符合预期,但是在 finally 块中添加 return 语句会使错误消失

Which is as expected, but adding a return statement in the finally block makes the error go away

public static void nocatch()
{
    try
    {
        throw new Exception();
    }
    finally
    {
        return; //makes the error go away! 
    }
}

有人可以解释一下发生了什么吗?以及为什么错误消失了?

Can someone please explain me what is going on? and why the error disappears?

注意:我编写此代码纯粹是出于实验目的!

Note : I wrote this code purely for experimental purposes!

推荐答案

该错误消失了,因为您的代码现在有效.(不好,但是有效.)

The error disappears because your code is now valid. (Not nice, but valid.)

如果 finally 块仅具有直接的 return; 语句,则总体try/catch/finally或try/finally语句不能抛出任何异常-因此您无需声明它可以引发异常.

If a finally block just has a straight return; statement, then the overall try/catch/finally or try/finally statement can't throw any exceptions - so you don't need to declare that it can throw an exception.

在您的原始代码中,您的 try 块可能(嗯,它会)抛出 Exception (或 CustomException >显然是在您的真实代码中)-这是一个已检查的异常,这意味着您必须捕获它或声明该方法可能会抛出它.

In your original code, your try block could (well, it will) throw Exception (or CustomException in your real code, apparently) - and that's a checked exception, which means you have to either catch it or declare that the method might throw it.

这篇关于最后添加return会隐藏异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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