Display Exception on try-catch clause
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).
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