简体   繁体   English

尝试使用switch语句捕获消息

[英]Try Catch message using switch statement

i am trying to catch a exception in the try catch block of my code. 我试图在我的代码的try catch块中捕获异常。 I have few errors such as wrong password/ file not found which have specific messages and i want to set codes if any of the error is found . 我有一些错误,例如未找到具有特定消息的错误密码/文件,并且如果发现任何错误,我想设置代码。 I am trying to catch the message using switch. 我正在尝试使用switch捕获消息。

  catch (Exception ex)
            {
  switch (ex.Message.ToString())
                {
                    case "Can't get attributes of file 'p'":
                        Debug.WriteLine("wrong username/password");
                        MainController.Status = "2";
                        break;
                    case "Can't get attributes of file 'p'.":
                        Debug.WriteLine("File is not Available");
                        MainController.Status = "3";
                        break;

                    default:
                        Debug.WriteLine("General FTP Error");
                        MainController.Status = "4";
                        break;
                }
}

i want to use message.contains method so that if i get any part of the error message in the ex.message then it should call the relevant case but i am not able to figure out how to use ex.message.contains . 我想使用message.contains方法,以便如果我在ex.message中得到错误消息的任何部分,那么它应该调用相关的情况,但我不知道如何使用ex.message.contains。 Can anyone help me ? 谁能帮我 ?

I would highly recommend refactoring your code to use custom exception handlers rather than rely on this "magic strings" approach. 我强烈建议将您的代码重构为使用自定义异常处理程序,而不要依靠这种“魔术字符串”方法。 This approach is not only difficult to maintain, but hard to test and debug, as spelling errors are not going to be caught by the compiler. 这种方法不仅难以维护,而且难以测试和调试,因为拼写错误不会被编译器捕获。

For example, you could create the following exception handlers: 例如,您可以创建以下异常处理程序:

// Note: can probably be better handled without using exceptions
public class LoginFailedException : Exception
{
    // ...
}

// Is this just a FileNotFound exception?
public class FileNotAvailableException : Exception
{
    // ...
}

public class FtpException : Exception
{
    // ...
}

You would then be able to catch each exception individually: 然后,您将能够分别捕获每个异常:

try
{
    // ...
}
catch (LoginFailedException)
{
    Debug.WriteLine("wrong username/password");
    MainController.Status = "2";
}
catch (FileNotAvailableException)
{
    Debug.WriteLine("File is not Available");
    MainController.Status = "3";
}
catch (FtpException)
{
    Debug.WriteLine("General FTP Error");
    MainController.Status = "4";
}

This approach is type-safe, and allows you to easily test and debug your methods. 这种方法是类型安全的,可让您轻松测试和调试方法。 It also prevents a typo from causing hours of difficult debugging. 它还可以防止输入错误导致数小时的困难调试。

不要这样做,而是对每种不同类型的Exception使用单独的catch块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM