Re-throwing Exception, Custom exception

This is a very straightforward post that I just want to highlight some important notes about exception

Re-throwing Exception?

We re-throw exception in many cases for example:

  • For logging

We catch and re-throw the original exception

  • For security purpose

Because we don’t want to reveal info to all users, because it may be used to hack the system, so we just logged the original exception and re-throw general exception “The process can’t be done in this time“, so the user that has admin privilege will be able to go to the event log or the place that we used for logging with confidence it’s an admin user.

  • For using business exception

Sometimes we want to use some custom exceptions to reflect the alternative scenarios for our business workflow, for example:

      • InvalidPasswordException
      • InsufficientFundException
      • Etc.

When we re-throw exception in case of logging we use throw without the object because if we use throw ex, this will change the Stack Trace to say that the exception originated in that place where it’s not.

[sourcecode language=”csharp”]

try
{

}
catch (Exception)

{

throw;

}
[/sourcecode]

When we create our custom exception, it’s better to make it Serializable and to do that fast it’s better to use Exception snippet

ExceptionSnippet

[sourcecode language=”csharp”]

using System.Runtime.Serialization;

[Serializable]
public class MyException : Exception
{
public MyException()
{
}

public MyException(string message)
: base(message)
{
}

public MyException(string message, Exception inner)
: base(message, inner)
{
}

protected MyException(
SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
[/sourcecode]

Share This: