I want to modify the Message
property in Exception
with additional info. For example the generated SQL
from EF
.
But I don't want to lose anything from the original Exception
. This will make me lose the stacktrace
:
catch (Exception ex)
{
throw ex;
}
These Exception
's are coming from the Data Layer. And I want to throw
them so that they can be logged with Elmah
.
What are my options?
Catching and throwing exceptions is an overhead and is useless (except if you do something with it before re-throw, i.e. log it), so the programmer will actually be confused, thinking there is a bug and not understanding what the original intent was.
Throwing an exception is as simple as using the "throw" statement. You then specify the Exception object you wish to throw. Every Exception includes a message which is a human-readable error description. It can often be related to problems with user input, server, backend, etc.
When an exception is thrown the method stops execution right after the "throw" statement. Any statements following the "throw" statement are not executed.
Exceptions are used to indicate that an error has occurred while running the program. Exception objects that describe an error are created and then thrown with the throw keyword.
If you want to add something you can just wrap it in another exception:
catch( Exception ex)
{
throw new Exception("my new message",ex);
}
and you will be able to access the inside exception with the full stack trace
Define your custom exception class, and put the original exception as the inner exception, and throw the wrapped exception:
public class CustomException : Exception
{
public CustomException()
: base()
{
}
public CustomException(string message)
: base(message)
{
}
public CustomException(string message, Exception innerException)
: base(message, innerException)
{
}
//...other constructors with parametrized messages for localization if needed
}
catch (Exception ex)
{
throw new CustomException("Something went wrong", ex);
}
Of course its name should be changed accordingly. This way you have full control on exceptions used in your domain, and you don't loose any information from the original throw.
It is very helpful, especially in large projects, to have custom exceptions with good class names. They help in diagnosing problems from first sight in many simple situations, without the need of reading into exception's details and debugging. The latter is needed only when some really elaborate problems occurs. Thus, throwing around bare Exception
instances wrapped around each other seems a bad practice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With