【问题标题】:How to handle various exceptions coming from an external function如何处理来自外部函数的各种异常
【发布时间】:2022-01-04 20:49:53
【问题描述】:

如何处理、调用 add 函数中的异常。 外部函数将根据条件抛出两个不同的异常。 我想在 main.js 中以不同的方式处理这些异常中的每一个。 感谢您的帮助。

我的示例代码:

        static void Main(string[] args)
        {
            try
            {
                add(0, 0);
            }
            catch(Exception ex)
            {
                if(Exception 1){
                    //...
                }
                if(Exception 2){
                    //...
                }               
            }          
        }

        public static int add (int a, int b)
        {
            int result = a + b;
            if (result == 0)
            {
                throw new Exception("Exception 1");
            }
            if(result > 10)
            {
                throw new Exception("Exception 2");
            }
            return result;
        }

【问题讨论】:

  • 不要扔System.Exception (link)
  • 不要使用异常来控制流量 (link)

标签: c#


【解决方案1】:

你必须使用你在add方法中分配的消息,然后检查main里面的条件或者你想要的其他地方 有解决方案的代码:

static void Main(string[] args)
    {

        try
        {
            add(0, 0);
        }
        catch (Exception ex)
        {
            Console.WriteLine("catch");

            if (ex.Message == "Exception 1")
            {
                Console.WriteLine("1");
            }
            if (ex.Message == "Exception 2")
            {
                Console.WriteLine("2");
            }
        }
    }



public static int add(int a, int b)
{
    int result = a + b;
    if (result == 0)
    {
        throw new Exception("Exception 1");
    }
    if (result > 10)
    {
        throw new Exception("Exception 2");
    }
    return result;
}

【讨论】:

    猜你喜欢
    • 2011-11-21
    • 1970-01-01
    • 2015-05-19
    • 2020-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-09
    • 2011-09-01
    相关资源
    最近更新 更多