How to change to error message

A

ad

I use try..catch(exception e) to catch excption and show to error(e.Message)
to user.
But the error is some difficult for user to understand.
How can I change the e.Message to some custom message.
 
S

Stoitcho Goutsev \(100\) [C# MVP]

ad,

You catch objects of type Exception, which means you handle all exceptions
in the same place. My suggestion is to filter down the exception that you
expect to be thrown by type. then in the event handlers instead
error(e.Message) you can emit most friently message.

try
{
}
catch(ExceptionType1 e1)
{
error("message1");
}
catch(ExceptionType2 e1)
{
error("message2");
}
catch(ExceptionType3 e1)
{
error("message3");
}
catch(Exception e)
{
// for unexpected exceptions you can show the original message or some
message in the line of the "unexpected error"
error(e.Message);
}

You have to always start from the more specific to the common exception
types. If you put catch(Exception e) as a first exception block it will
catch all the exception and the execution will never enter the other blocks.


HTH
Stoitcho Goutsev (100) [C# MVP]
 
C

Carlos J. Quintero [.NET MVP]

You can´t change the Message property of an Exception, but you can throw a
new exception with the text that you want passing the caught exception as
inner exception:

....
catch Exception ex
{
throw new ApplicationException("my text", ex);
}

--

Best regards,

Carlos J. Quintero

MZ-Tools: Productivity add-ins for Visual Studio .NET, VB6, VB5 and VBA
You can code, design and document much faster.
Free resources for add-in developers:
http://www.mztools.com
 
N

Nicholas Paldino [.NET/C# MVP]

ad,

I would recommend that in the case of exceptions, you do not try and
show a friendly message at all. Rather, you should be checking the
conditions in your code that you can anticipate, and then displaying error
information when those conditions are not met.

Using exceptions as a way of handling logic errors is not the best of
approaches. For example, if you are trying to open a file, you should check
to see if the file exists first before trying to open it, instead of relying
on a FileNotFoundException being thrown.

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top