【问题标题】:Catching exceptions from other methods从其他方法捕获异常
【发布时间】:2014-03-12 16:49:02
【问题描述】:

我有一个包含多个方法的类。

其中一个方法在 while 循环 (MainMethod) 中运行。

我从 MainMethod 调用同一类中的辅助方法。

Try Catch 包含在大部分执行发生的 MainMethod 中。

如果在不包含 Try Catch 的辅助方法中发生异常,是否会被进一步捕获?即在调用辅助方法的 MainMethod 内部。

     class Class1
     {
        public MainMethod() 
        {
            while (true) 
            {
                try 
                {
                    // ...
                    // ...
                    // ...
                    HelperMethod();
                    // ...
                    // ...
                }
                catch (Exception e) 
                {
                    // Console.WriteLine(e.ToString());
                    // logger.log(e.ToString();
                    // throw e;
                    // ...
                }

            }
        }

        public HelperMethod() 
        {
            // No Try Catch
            // if (today == "tuesday") program explodes.
        }
    }

谢谢。

【问题讨论】:

  • 为什么不从HelperMethod 抛出异常,看看自己呢?
  • 感谢投反对票
  • 我在这里问的原因是因为我知道它会很快得到答复。它也可以作为任何想知道同样事情的人的资源。

标签: c# exception exception-handling


【解决方案1】:

是的。如果一个方法没有 try/catch 块,它将“冒泡”堆栈并被链上的下一个处理程序捕获。如果没有处理程序,那是您的程序因“未处理”异常而终止的时候。

【讨论】:

  • 谢谢,这正是我想要的。
【解决方案2】:

是的,它会的。像这样的:

public class Helper
{
    public void SomeMethod()
    {

        throw new InvalidCastException("I don't like this cast.");
    }

    public void SomeOtherMethod()
    {
        throw new ArgumentException("Your argument is invalid.");
    }
}

public class Caller
{
    public void CallHelper()
    {
        try
        {
            new Helper().SomeMethod();

        }
        catch (ArgumentException exception)
        {
            // Do something there
        }
        catch (Exception exception)
        {
            // Do something here
        }

        try
        {
            new Helper().SomeOtherMethod();
        }
        catch (ArgumentException exception)
        {
            // Do something there
        }
        catch (Exception exception)
        {
            // Do something here
        }
    }
}

请注意,如果调用者应用程序处理该特定类型的异常,则会调用特定的 catch 块。

恕我直言,最好处理您从代码中调用的方法可能引发的特定异常。但是,这也意味着您正在调用的方法的作者创建了一个体面的文档共享异常,我们需要从他的代码中获得这些异常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 2013-09-17
    • 2011-05-26
    • 1970-01-01
    • 2015-11-24
    相关资源
    最近更新 更多