简体   繁体   中英

Display Exception on try-catch clause

Up to now, whenever I wanted to show an exception thrown from my code I used:

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

I used the above code mainly for debugging reasons, in order to see the exact type of exception and the according reason the exception was thrown.

In a project I am creating now, I use several try-catch clauses and I would like to display a popup message in case of an exception, to make it more "user friendly". By "user friendly", I mean a message that would hide phrases like Null Reference Exception or Argument Out Of Range Exception that are currently displayed with the above code.

However I still want to see relevant info with the type of exception that created the message.

Is there a way to format the displayed output of thrown exceptions according to previous needs?

You can use .Message , however I wouldn't recommend just catching Exception directly. Try catching multiple exceptions or explicitly state the exception and tailor the error message to the Exception type.

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

Catching Exception is rather generic and can be deemed bad practice, as it maybe hiding bugs in your application.

You can also check the exception type and handle it accordingly by checking the Exception type:

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;
   }
}

Which would show a message box to the user if the Exception is an ArgumentOutOfRange or FormatException, otherwise it will rethrow the Exception (And keep the original stack trace).

Exception.Message provides a more (but not entirely) user-friendly message than Exception.ToString() . Consider this contrived example:

try
{
    throw new InvalidOperationException();
}
catch(InvalidOperationException ex)
{
    Console.WriteLine(ex.ToString());
}

Although Message yields a simpler message than ToString() the message displayed will still not mean much to the user. It won't take you much effort at all to manually swallow exceptions and display a custom message to the user that will assist them in remedying this issue.

try
{
    using (StreamReader reader = new StreamReader("fff")){}
}
catch(ArgumentException argumentEx)
{
    Console.WriteLine("The path that you specified was invalid");
    Debug.Print(argumentEx.Message);

}
catch (FileNotFoundException fileNotFoundEx)
{
    Console.WriteLine("The program could not find the specified path");
    Debug.Print(fileNotFoundEx.Message);
}

You can even use Debug.Print to output text to the immediate window or output window (depending on your VS preferences) for debugging purposes.

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

Use above code.

Can also show custom error message as:

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

Additional :

For difference between ex.toString() and ex.Message follow:

Exception.Message vs Exception.ToString()

All The details with example:

http://www.dotnetperls.com/exception

You can use Exception.Message property to get a message that describes the current exception.

  catch (Exception ex)
   {
     MessageBox.Show(ex.Messagge());         
   }

try this code :

      try
      {
        // Code that may throw different exceptions
      }
      catch (Exception exp)
      {
           MessageBox.Show(exp.Message());         
      }

The trick is using the Message method of the exception:

catch (Exception ex)
{
    MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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