代码之家  ›  专栏  ›  技术社区  ›  dafna

引发级联异常

  •  0
  • dafna  · 技术社区  · 6 年前

    我想将多个错误消息传递给GUI。我该怎么做?请看一下我上面的抽象例子:

    try
    {
        LogIn(usr, pwd); //entry point
    }
    catch(Exception ex)
    {
        throw new Exception("Login failed.");
    }
    
    
    
    public void LogIn(string usr, string pwd) {
    
        if(usr == "") {
            throw new Exception("Username was empty.");
        }
    
        if(pwd== "") {
            throw new Exception("Password was empty.");
        }
    
        try
        {
            //do some other stuff without a more specific error message
        }
        catch
        {
            throw;
        }  
    }
    

    稍后我想得到一个结果错误消息,如

    登录失败。密码为空。

    如果用户没有输入密码。现在我只得到最上面的最后一条错误消息(“login failed.”),所以只有一半的信息我想给用户。

    3 回复  |  直到 6 年前
        1
  •  3
  •   Smartis has left SO again    6 年前

    我会重新考虑你的结构。 正如评论中指出的,有一些事情需要考虑:

    接近 List<string> 收集问题:

    public void LogIn(string usr, string pwd) 
    {   
        List<string> errors = new List<string>();
    
        if(string.IsNullOrEmpty(usr)) 
        {
            errors.Add("Username is empty.");
        }
    
        if(string.IsNullOrEmpty(pwd)) 
        {
            errors.Add("Password is empty.");
        }   
    
        if(errors.Count > 0) // If errors occur, throw exception.
        {
            throw new Exception(string.Join("\r\n",errors));
        }   
    }
    
        2
  •  4
  •   Damien_The_Unbeliever    6 年前

    你可以 例外情况:

    try
    {
        LogIn(usr, pwd); //entry point
    }
    catch(Exception ex)
    {
        throw new Exception("Login failed.", ex);
    }
    

    注意第二个参数,然后 InnerException 财产 Exception .

    但是在做之前,考虑一下上面的块是否 增加任何价值 . 如果你让 Password was empty 相反,调用方仍然会知道,一般来说,登录失败了,仅此异常似乎就包含了所有必需的信息。

    只有 catch 如果你有什么异常 有用的 要执行的操作-如果可以恢复错误条件,请添加信息或不想向调用方公开实现详细信息。否则,让异常上升到有用的程度 可以 完成。

        3
  •  1
  •   Meikel    6 年前

    你可以用 ex.Message 要么就是 密码为空。 用户名为空。