代码之家  ›  专栏  ›  技术社区  ›  Matt H

是否尝试/最终忽略异常?

  •  10
  • Matt H  · 技术社区  · 17 年前

    在这种情况下,无论发生什么情况,我都希望执行某些代码,但我也需要将异常传递到堆栈上,以便稍后处理。详情如下:

    
    try
    {
      // code
    }
    finally
    {
      // code that must run
    }
    

    我们将忽略任何异常,还是将它们传递给其他人?我的测试似乎表明,他们仍然通过了,但我想确定我没有疯。

    4 回复  |  直到 17 年前
        1
  •  18
  •   RichieHindle    17 年前

    这个 finally try/finally -使某些代码始终运行,即使在抛出异常时也是如此。

    但正如亚当在他的评论和山姆在他的回答中指出的那样,有些语言需要注意。

        2
  •  9
  •   Carl Manaster    17 年前

    下面是一个测试类,它显示(1)最终运行,不管是否抛出异常;和(2)将异常传递给调用方。

    public class FinallyTest extends TestCase {
        private boolean finallyWasRun   = false;
    
        public void testFinallyRunsInNormalCase() throws Exception {
            assertFalse(finallyWasRun);
            f(false);
            assertTrue(finallyWasRun);
        }
    
        public void testFinallyRunsAndForwardsException() throws Exception {
            assertFalse(finallyWasRun);
            try {
                f(true);
                fail("expected an exception");
            } catch (Exception e) {
                assertTrue(finallyWasRun);
            }
        }
    
        private void f(boolean withException) throws Exception {
            try {
                if (withException)
                    throw new Exception("");
            } finally {
                finallyWasRun = true;
            }
        }
    }
    
        3
  •  3
  •   Community Mohan Dere    9 年前

    假设这是C#,那么finally将始终运行,除非您获得 StackOverflowException 或者 ExecutingEngineException

    此外,像ThreadAbortException这样的异步异常可能会中断finally块的流,导致它部分执行。

    见相关问题:

    In C# will the Finally block be executed in a try, catch, finally if an unhandled exception is thrown?

        4
  •  2
  •   marcc    17 年前

    :

    这里的答案是正确的,finally运行,异常被“忽略”。但为了说明解决这个问题是多么容易:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                throw new Exception("testing");
            }
            finally
            {
                Console.WriteLine("Finally");
            }
        }
    }
    

    运行这个简单的小控制台应用程序时,抛出异常,然后执行finally块。

    推荐文章