在try-catch子句上显示异常

apo*_*ene 15 .net c# exception try-catch

到目前为止,每当我想显示我使用的代码抛出异常时:

try
{
    // Code that may throw different exceptions
}
catch (Exception ex)
{
    MessageBox.Show(ex.ToString());         
}
Run Code Online (Sandbox Code Playgroud)

我使用上面的代码主要是出于调试原因,以便查看异常的确切类型以及抛出异常的相应原因.

在我正在创建的项目中,我使用了几个try-catch子句,并且我想在出现异常时显示弹出消息,以使其更加"用户友好".通过"用户友好",我的意思是一条消息,它将隐藏当前使用上述代码显示的Null Reference ExceptionArgument Out of Range Exception等短语.

但是,我仍然希望查看与创建消息的异常类型相关的信息.

有没有办法根据以前的需要格式化抛出异常的显示输出?

Dar*_*ren 11

你可以使用.Message,但我不建议直接捕捉Exception.尝试捕获多个异常或显式声明异常并将错误消息定制到Exception类型.

try 
{
   // Operations
} 
catch (ArgumentOutOfRangeException ex) 
{
   MessageBox.Show("The argument is out of range, please specify a valid argument");
}
Run Code Online (Sandbox Code Playgroud)

捕获Exception是相当通用的,可以被认为是不好的做法,因为它可能会隐藏应用程序中的错误.

您还可以通过检查异常类型来检查异常类型并相应地处理它:

try
{

} 
catch (Exception e) 
{
   if (e is ArgumentOutOfRangeException) 
   { 
      MessageBox.Show("Argument is out of range");
   } 
   else if (e is FormatException) 
   { 
      MessageBox.Show("Format Exception");
   } 
   else 
   {
      throw;
   }
}
Run Code Online (Sandbox Code Playgroud)

如果Exception是ArgumentOutOfRange或FormatException,那么会向用户显示一个消息框,否则它将重新抛出异常(并保留原始堆栈跟踪).


Fre*_*cer 7

try
     {
        /////Code that  may throws several types of Exceptions
     }    
     catch (Exception ex)
       {
         MessageBox.Show(ex.Message);         
       }
Run Code Online (Sandbox Code Playgroud)

使用上面的代码。

还可以将自定义错误消息显示为:

try
     {
        /////Code that  may throws several types of Exceptions
     }    
     catch (Exception ex)
       {
         MessageBox.Show("Custom Error Text "+ex.Message);         
       }
Run Code Online (Sandbox Code Playgroud)

额外的 :

对于 ex.toString() 和 ex.Message 之间的区别如下:

Exception.Message 与 Exception.ToString()

所有详细信息与示例:

http://www.dotnetperls.com/exception