在C#中捕获自定义异常

Hat*_*oin 6 c# custom-exceptions

我创建了一个自定义异常类,如下所示

namespace testingEXception
{
    public class CustomException : Exception
    {            
        public CustomException()
        {
        }
        public CustomException(string message)
            : base(message)
        {
        }

        public CustomException(string message, Exception innerException)
            : base(message, innerException)
        {

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我在相同的解决方案中从另一个项目抛出异常

namespace ConsoleApplication1
{
    public class testClass
    {
        public void compare()
        {
            if (1 > 0)
            {
                throw new CustomException("Invalid Code");
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

并像这样抓住它

    namespace testingEXception
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                testClass obj = new testClass();
                obj.compare();

            }
            catch (testingEXception.CustomException ex)
            {
                //throw;
            }
            catch (Exception ex)
            {
               // throw new CustomException(ex.Message);
            }

            Console.ReadKey();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是,尽管异常类型显示CustomException,但异常不会被第一个捕获捕获,而是被第二个捕获捕获。

Pet*_*hie 2

您需要提供更多详细信息,以下代码输出“CustomException”:

try
{
    throw new CustomException("Invalid code.");
}
catch (CustomException ex)
{
    System.Diagnostics.Trace.WriteLine("CustomException");
    throw;
}
catch (Exception ex)
{
    throw;
}
Run Code Online (Sandbox Code Playgroud)

具有以下课程:

public class CustomException : Exception
{
    public CustomException()
    {
    }
    public CustomException(string message)
        : base(message)
    {
    }

    public CustomException(string message, Exception innerException)
        : base(message, innerException)
    {

    }
}
Run Code Online (Sandbox Code Playgroud)

更新:

关于优化和优化throw:这不可能发生,因为任何特定的代码块都无法知道堆栈中较高层的调用者是否可以捕获代码CustomException。引发异常是一种可见的副作用,CLI 中有各种保证来确保这些可见的副作用保持可见。

此外,try、catch 和finally 块在CLI 中是“受保护区域”。这些区域的特殊之处在于,区域内具有“可见”副作用的操作不能对其可见副作用进行重新排序。有关更多详细信息,请参阅http://lynk.at/qH8SHkhttp://lynk.at/pJcg98