C#如何捕获异常并检查它是否包含字符串?

时间:2021-07-10 07:20:11

I'm getting an exception which says "Access Denied" when the users permissions are sufficient, how do I catch an exception and check for "Access Denied" so that I can show the user a friendlier "Sorry Access Denied" message?

当用户权限足够时,我收到一个说“拒绝访问”的异常,如何捕获异常并检查“拒绝访问”,以便我可以向用户显示更友好的“拒绝访问被拒绝”消息?

Thanks Beginner :-)

谢谢初学者:-)

7 个解决方案

#1


15  

You don't really want to check the string of the message, you want to check the type of the message, which can be easily done by catching only the type(s) of exception you are checking for. The following example will catch two different types of exceptions and do different actions based on what if any error occurs. (Note: the names of the exceptions are made up)

您真的不想检查消息的字符串,您想要检查消息的类型,这可以通过仅捕获您正在检查的异常类型来轻松完成。以下示例将捕获两种不同类型的异常,并根据发生的错误执行不同的操作。 (注意:组成例外的名称)

try {
    ...
} catch (SomeKindOfException ex) {
    MessageBox.Show(ex.Message);
} catch (AccessDeniedException ex) {
    //Do something else
}

#2


10  

I think the safest thing to do here (and surprisingly none of the answers show this) is to

我认为这里最安全的事情(令人惊讶的是,没有一个答案表明这一点)是

  • Catch as specific an exception type as you can. Really try to avoid catching all exceptions.
  • 尽可能捕获特定的异常类型。真的试图避免捕获所有异常。

  • Test the exception message for string.ToLowerInvariant() containing your target string.
  • 测试包含目标字符串的string.ToLowerInvariant()的异常消息。

  • re-throw if it's not what you expect!
  • 如果它不是你所期望的那样重新投掷!

like so:

try
{
    int result = DoStuff(param);
}
catch (System.IO.IOException ioex)
{
    if (ioex.Message.ToLowerInvariant().Contains("find me"))
    {
        .. do whatever ..
    }
    else
    {
        // no idea what just happened; we gotta crash
        throw;
    }
}

#3


6  

If you are using a try catch block...

如果您正在使用try catch块...

try
{
    //error occurs
}
catch (Exception ex)
{
    MessageBox.show(ex.Message);
}

Obviously that is pretty crappy error handling, but it shows that the Exception object contains the error string. You can narrow down the handling of different exceptions by catching different exception types.

显然,这是非常糟糕的错误处理,但它显示Exception对象包含错误字符串。您可以通过捕获不同的异常类型来缩小对不同异常的处理范围。

Try
{
    //error occurs
}
catch (AccessDeniedException ex)
{
    MessageBox.show(ex.Message);
}
catch (FieldAccessException)
{

}
// etc...

#4


2  

Simple:

try
{
    YourCommandWhichResultsInDeniedAccess();
}
catch (AccessDeniedException)
{
    MessageBox.Show('Access Denied');
}

If you don't know the type of the Exception and/or you want to check the Exception message instead, do the following:

如果您不知道异常的类型和/或您想要检查异常消息,请执行以下操作:

try
{
    YourCommandWhichResultsInDeniedAccess();
}
catch (Exception e)
{
   if (e.Message == 'Access Denied')
   {
       MessageBox.Show('Access Denied')
   }
}

#5


1  

Using exception filters in C# 6.0 it is even easier:

在C#6.0中使用异常过滤器更容易:

try
{
    int result = DoStuff(param);
}
catch (IOException ex) 
when (ex.Message.ToLowerInvariant().Contains("find me")) {
{
    //.. do whatever ..
}

#6


0  

Just a modification from above, but working with datatable and database and dropdownlist

只是从上面修改,但使用数据表和数据库和下拉列表

try {
        drop_grup_head.SelectedValue = ds.Rows[0]["group_head"].ToString();
     }
     catch (Exception exce ) {
        if (exce.Message.ToLowerInvariant().Contains("does not exist in the list")) {
           drop_grup_head.SelectedValue = "0";
        }
     }

#7


-2  

First off - should look into the permissions issue rather than tackling the exception solely. If "Access Denied" is thrown then there must either be a permissions issues or a lock of some sort.

首先 - 应该查看权限问题而不是仅仅处理异常。如果抛出“拒绝访问”,则必须存在权限问题或某种锁定。

Anyways, "Message" is a string and you can use the .Contains method on it to check for "Access Denied".

无论如何,“Message”是一个字符串,您可以使用.Contains方法检查“拒绝访问”。

You can't change the "Message" property as it has no setter, but you can handle the exception and display a polite message.

您无法更改“Message”属性,因为它没有setter,但您可以处理异常并显示礼貌消息。

MessageBox.Show("Sorry, Access Denied"); for instance.

MessageBox.Show(“抱歉,拒绝访问”);例如。

Edit: as mentioned above you should check for the type of exception. e.g. AccessDeniedException rather than use something as generic as "Exception".

编辑:如上所述,您应该检查异常的类型。例如AccessDeniedException而不是像“Exception”那样使用泛型。


try
        {
            // code here which throws exception
        }
        catch (Exception ex)
        {
            if (ex.Message.Contains("Access Denied"))
            {
                MessageBox.Show("Sorry, Access Denied", "This is a polite error message");
            }
        }

#1


15  

You don't really want to check the string of the message, you want to check the type of the message, which can be easily done by catching only the type(s) of exception you are checking for. The following example will catch two different types of exceptions and do different actions based on what if any error occurs. (Note: the names of the exceptions are made up)

您真的不想检查消息的字符串,您想要检查消息的类型,这可以通过仅捕获您正在检查的异常类型来轻松完成。以下示例将捕获两种不同类型的异常,并根据发生的错误执行不同的操作。 (注意:组成例外的名称)

try {
    ...
} catch (SomeKindOfException ex) {
    MessageBox.Show(ex.Message);
} catch (AccessDeniedException ex) {
    //Do something else
}

#2


10  

I think the safest thing to do here (and surprisingly none of the answers show this) is to

我认为这里最安全的事情(令人惊讶的是,没有一个答案表明这一点)是

  • Catch as specific an exception type as you can. Really try to avoid catching all exceptions.
  • 尽可能捕获特定的异常类型。真的试图避免捕获所有异常。

  • Test the exception message for string.ToLowerInvariant() containing your target string.
  • 测试包含目标字符串的string.ToLowerInvariant()的异常消息。

  • re-throw if it's not what you expect!
  • 如果它不是你所期望的那样重新投掷!

like so:

try
{
    int result = DoStuff(param);
}
catch (System.IO.IOException ioex)
{
    if (ioex.Message.ToLowerInvariant().Contains("find me"))
    {
        .. do whatever ..
    }
    else
    {
        // no idea what just happened; we gotta crash
        throw;
    }
}

#3


6  

If you are using a try catch block...

如果您正在使用try catch块...

try
{
    //error occurs
}
catch (Exception ex)
{
    MessageBox.show(ex.Message);
}

Obviously that is pretty crappy error handling, but it shows that the Exception object contains the error string. You can narrow down the handling of different exceptions by catching different exception types.

显然,这是非常糟糕的错误处理,但它显示Exception对象包含错误字符串。您可以通过捕获不同的异常类型来缩小对不同异常的处理范围。

Try
{
    //error occurs
}
catch (AccessDeniedException ex)
{
    MessageBox.show(ex.Message);
}
catch (FieldAccessException)
{

}
// etc...

#4


2  

Simple:

try
{
    YourCommandWhichResultsInDeniedAccess();
}
catch (AccessDeniedException)
{
    MessageBox.Show('Access Denied');
}

If you don't know the type of the Exception and/or you want to check the Exception message instead, do the following:

如果您不知道异常的类型和/或您想要检查异常消息,请执行以下操作:

try
{
    YourCommandWhichResultsInDeniedAccess();
}
catch (Exception e)
{
   if (e.Message == 'Access Denied')
   {
       MessageBox.Show('Access Denied')
   }
}

#5


1  

Using exception filters in C# 6.0 it is even easier:

在C#6.0中使用异常过滤器更容易:

try
{
    int result = DoStuff(param);
}
catch (IOException ex) 
when (ex.Message.ToLowerInvariant().Contains("find me")) {
{
    //.. do whatever ..
}

#6


0  

Just a modification from above, but working with datatable and database and dropdownlist

只是从上面修改,但使用数据表和数据库和下拉列表

try {
        drop_grup_head.SelectedValue = ds.Rows[0]["group_head"].ToString();
     }
     catch (Exception exce ) {
        if (exce.Message.ToLowerInvariant().Contains("does not exist in the list")) {
           drop_grup_head.SelectedValue = "0";
        }
     }

#7


-2  

First off - should look into the permissions issue rather than tackling the exception solely. If "Access Denied" is thrown then there must either be a permissions issues or a lock of some sort.

首先 - 应该查看权限问题而不是仅仅处理异常。如果抛出“拒绝访问”,则必须存在权限问题或某种锁定。

Anyways, "Message" is a string and you can use the .Contains method on it to check for "Access Denied".

无论如何,“Message”是一个字符串,您可以使用.Contains方法检查“拒绝访问”。

You can't change the "Message" property as it has no setter, but you can handle the exception and display a polite message.

您无法更改“Message”属性,因为它没有setter,但您可以处理异常并显示礼貌消息。

MessageBox.Show("Sorry, Access Denied"); for instance.

MessageBox.Show(“抱歉,拒绝访问”);例如。

Edit: as mentioned above you should check for the type of exception. e.g. AccessDeniedException rather than use something as generic as "Exception".

编辑:如上所述,您应该检查异常的类型。例如AccessDeniedException而不是像“Exception”那样使用泛型。


try
        {
            // code here which throws exception
        }
        catch (Exception ex)
        {
            if (ex.Message.Contains("Access Denied"))
            {
                MessageBox.Show("Sorry, Access Denied", "This is a polite error message");
            }
        }