Display Exception on try-catch clause
Solution 1
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).
Solution 2
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
Solution 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.
Solution 4
try this code :
try
{
// Code that may throw different exceptions
}
catch (Exception exp)
{
MessageBox.Show(exp.Message());
}
Solution 5
You can use Exception.Message property to get a message that describes the current exception.
catch (Exception ex)
{
MessageBox.Show(ex.Messagge());
}
apomene
Software Engineer. The more I expand the island of my learning's, the more I conceive the ocean of things I don't know
Updated on January 22, 2021Comments
-
apomene over 3 years
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?
-
devdigital about 11 yearsYou 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.
-
Alvin Wong about 11 yearsIf 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.
-
Amitd about 11 yearsBetter 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
-
apomene about 11 yearsI 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
-
-
Arshad about 11 years
MessageBox.Show(ex.Message);
-
Alvin Wong about 11 yearsYou forgot the last case where you'll need to
throw;
the exception again. -
default about 11 yearsin your second example, you could use
throw;
in order to propagate it further in the try chain -
Ilya Ivanov about 11 yearswhat the problem of writing several
catch
clauses withArgumentOutOfRangeException
andFormatException
, instead of writingif else
statements in onecatch
block -
Darren about 11 years@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. -
Ilya Ivanov about 11 yearsok, agree, I just thought it would be better to teach in the in advance on how to properly organize your catch blocks.