throwing custom message?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

How can I catch an error and throw the exception message plus some custom text?
For example, I'd like to do something like this:
try
{
//generate error
}
catch
{
//throw ex + " my custom message";
// OR
//throw ex.Message + " my custom message";
}

How is this possible without writing my own custom exception class?

Thanks.
 
generally you would wrap it in an applicationException

eg

try
{
}
catch(Exception ex)
{
throw new ApplicationException("your message here", ex);
}

dont forget to include the original exception as the second parameter - this
way u can look at the original exception later when u handle this.
 
How can I catch an error and throw the exception message plus some custom text?
<Snip>

VMI,

You can throw an exception with a custom error message without writing a
custom exception class. Inside your catch block, just throw the most
appropriate pre-defined exception type with your modified error message.

Note, it is generally considered best practice to throw a fairly specific
exception instead of the generic System.Exception. Let's say if you have a
stub method that is not supported yet, you should throw a
NotSupportedException. Or if you are validating inputs inside a function
call you might throw a InvalidArgument exception. Otherwise you might throw
an ApplicationException.

Here is an example.

sbyte i = 127;
try
{
// Generates an overflow error. Signed byte can only hold
values from -128 to 127..
checked {
i = (sbyte) (i+1);
}
}
catch (Exception ex)
{
// Throw an exception with a modified error message.
throw new ApplicationException("Something went wrong here: " +
ex.Message);
}

Useful links for exception handling guidelines
http://www.codeproject.com/dotnet/e...#Don'tcatch(Exception)morethanonceperthread12

http://msdn2.microsoft.com/en-us/library/8ey5ey87(VS.71).aspx

Hope this helps,
Jason Vermillion
 
I would prefer the way XOR offered.
By Using "throw new ApplicationException("your message here", ex);" to
throw an Exception with a CustomText you won't loose the original
Exception, because it is kept in the InnerException Property
 

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

Back
Top