C# 从其他方法捕获异常

C# 从其他方法捕获异常,c#,exception,exception-handling,C#,Exception,Exception Handling,我有一个包含几个方法的类 其中一个方法在while循环中运行(main方法) 我从MainMethod调用同一类中的helper方法 Try-Catch包含在main方法中,大部分执行发生在main方法中 如果在不包含Try-Catch的helper方法中发生异常,它会被进一步捕获吗?i、 e.调用helper方法的内部main方法 class Class1 { public MainMethod() { while

我有一个包含几个方法的类

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

我从MainMethod调用同一类中的helper方法

Try-Catch包含在main方法中,大部分执行发生在main方法中

如果在不包含Try-Catch的helper方法中发生异常,它会被进一步捕获吗?i、 e.调用helper方法的内部main方法

     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.
        }
    }

谢谢。

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

是的。大概是这样的:

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块


总之,处理您从代码中调用的方法可能引发的特定异常是很好的。然而,这也意味着你调用的方法的作者创建了一个不错的文档共享异常,我们需要从他的代码中得到它。

你为什么不从
HelperMethod
中抛出一个异常,看看你自己呢?感谢你的拒绝。我在这里问这个问题的原因是因为我知道它会很快得到回答。对于任何想知道同样事情的人来说,它也是一种资源。谢谢,这正是我想要的。