17

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?

Carsten
  • 11,287
  • 7
  • 39
  • 62
apomene
  • 14,282
  • 9
  • 46
  • 72
  • You can display any type of message you wish, or react to the exception in any number of ways, you're in control once you've caught the exception. – devdigital Apr 22 '13 at 10:58
  • If you're going to debug, why don't just use a debugger? If any unexpected exceptions occurs in end-user, just log it and let the program terminates. – Alvin Wong Apr 22 '13 at 10:58
  • 2
    Better to add a message for each exception instead of just 1..add multiple catch blocks and add msgbox in each. don't catch exception directly – Amitd Apr 22 '13 at 10:59
  • I have problem now...you all provided with helpful answers and I don't know which one to pick as correct.. Basically the difference between ex.toString() and ex.Message that almost everybody mention is the think that helps – apomene Apr 22 '13 at 11:07

6 Answers6

14

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).

Darren
  • 68,902
  • 24
  • 138
  • 144
  • You forgot the last case where you'll need to `throw;` the exception again. – Alvin Wong Apr 22 '13 at 11:03
  • in your second example, you could use `throw;` in order to propagate it further in the try chain – default Apr 22 '13 at 11:03
  • what the problem of writing several `catch` clauses with `ArgumentOutOfRangeException` and `FormatException`, instead of writing `if else` statements in one `catch` block – Ilya Ivanov Apr 22 '13 at 11:08
  • @IlyaIvanov - I would recommend the former as I think it's cleaner IMO. I was demonstrating that you can check the type of Exception (if you caught the generic Exception type), however my main point is that I rather explicitly state the types to be caught than catching `Exception` directly. – Darren Apr 22 '13 at 11:10
  • ok, agree, I just thought it would be better to teach in the in advance on how to properly organize your catch blocks. – Ilya Ivanov Apr 22 '13 at 11:19
6
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

Community
  • 1
  • 1
Freelancer
  • 9,008
  • 7
  • 42
  • 81
3

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.

User 12345678
  • 7,714
  • 2
  • 28
  • 46
2

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

  catch (Exception ex)
   {
     MessageBox.Show(ex.Messagge());         
   }
Mohammad Arshad Alam
  • 9,694
  • 6
  • 38
  • 61
2

try this code :

      try
      {
        // Code that may throw different exceptions
      }
      catch (Exception exp)
      {
           MessageBox.Show(exp.Message());         
      }
nassimlouchani
  • 423
  • 4
  • 8
1

The trick is using the Message method of the exception:

catch (Exception ex)
{
    MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
Alenros
  • 816
  • 7
  • 23