抛出自定义异常时如何显示错误消息

时间:2016-09-25 19:03:28

标签: c# wpf xaml

我刚刚开始使用主题exceptionhandling。我读了很多关于它的positiv的东西,所以我认为我应该这样做,因为我目前使用错误代码的技术真的很难看......

好的,我们有以下场景:用户在textbox中输入了密码。按下登录按钮后,他会收到一个积极或消极的消息。

MainWindow.xaml

<TextBox x:Name="txtBoxUserPassword/>
<Button x:Name="btnLogin" Click="btnLogin_Click">Login</Button>

MainWindow.xaml.cs

private void btnCT_Click(object sender, RoutedEventArgs e)
{
     DataBase db = new DataBase();
     db.IsPasswordCorrect(this.txtBoxUserPassword.Text);

     // How can I catch here the exception from the class to 
     // show the error notification?
}

DataBase.cs

public class DataBase{
     public void IsPasswordCorrect(string password)
     {
          try{
              if(password != "fooBar")
              {
                  throw new InvalidPasswordException("You entered the wrong password. Try it again.");
              }
              else
              {
                  /*
                     ...
                  */
              }
          }
          catch(InvalidPasswordException ex){
              // What should I do here? I want to give the user an 
              // error message with the content "You entered the wrong   
              // password. Try it again."
          }
     }
}

InvalidPasswordException.cs

public class InvalidPasswordException: Exception
{
    public InvalidPasswordException(string message, Exception inner)
        : base(message, inner)
    {
    }
}

如您所见,这是我第一次使用exceptions。希望你能帮助我一点。谢谢!

修改

switch/case construct内有public void btnCT_Click()

switch (CheckString("EnteredString"))
{
    case 1:
        MessageBox.Show("Error 1");
        break;
    case 2:
        MessageBox.Show("Error 2");
        break;
    case 3:
        MessageBox.Show("Error 3");
        break;
    case 0:
        MessageBox.Show("Successful");
        break;
    }

这是我从另一个班级开始的方法。类名不重要。

public int CheckString(string enteredString)
{
    if(enteredString length is larger 25 chars)
        return 1;
    else if(enteredString contains special characters)
        return 2;
    else if(enteredString dosent contain any number)
        return 3; 
    else
        return 0;
}

1 个答案:

答案 0 :(得分:3)

我要说的第一件事就是你不需要为此而自定义例外。仅仅查看方法的名称(for mutation in queue { mutation.handleMutation(forState: state) } ),任何人都希望此方法返回true / false布尔值而不是异常。

所以你可以有一个更简单的

IsPasswordCorrect

但是,如果你真的需要抛出一个异常(请记住,这在性能方面是一个代价高昂的操作),那么不要在抛出它的方法中捕获它,而是让它冒泡到达调用代码< / p>

public class DataBase
{
     public bool IsPasswordCorrect(string password)
     {
          if(password != "fooBar")
             return false;
          else
             return true;
     }
}

.... at the UI level ....
if(!db.IsPasswordCorrect("notA_fooBar"))
   MessageBox.Show("You entered the wrong password. Try again");
else
   ....

并在调用代码中(在UI级别)添加try catch块

 public bool IsPasswordCorrect(string password)
 {
      if(password != "fooBar")
         throw new InvalidPasswordException("You entered the wrong password. Try again");
      ....
 }

在任何情况下,异常仅应用于例外原因。您不能使用它们来驱动代码。在这种情况下,最好的方法是返回一个真/假值。

当失败原因很复杂时,我通常会使用这种方法

private void btnCT_Click(object sender, RoutedEventArgs e)
{
     try
     {

          DataBase db = new DataBase();
          db.IsPasswordCorrect(this.txtBoxUserPassword.Text);

          // If you reach this point the password is correct
          // But it is ugly and unclear to any reader....

     }
     catch(InvalidPasswordException ex)
     {
         MessageBox.Show(ex.Message);
     }

当然,数据库类中的每个布尔方法,当有理由失败并返回false之前,会设置一个全局变量,其中包含失败所涉及的确切错误消息,因此客户端代码可以轻松处理消息。已完成通话。

相关问题