How can I throw exception gracefully?
public void Test()
{
if (error != 0) {
string msg = "Error";
throw new Exception(msg);
}
// Other function
...
}
I have also change the throw new Exception(msg); with logger
public void Test()
{
if (error != 0) {
string msg = "Error";
//throw new Exception(msg);
logger.Error(msg);
}
// Other function
...
}
Should I use Exit function to exit the function when error hit?
Thnak you.
You want to log before you throw the exception.
You also want to throw an exception type that inherits from System.Exception so consumers can catch specific types.
Throwing the exception will exit the function (actually will process a finally block first if you have one) so you only need to throw.
Also, if you’re catching a different exception in an error condition, you can log and then simply call throw; to throw the original exception and not trash the stack. If you want to throw your own
exception type in that case, you can include the original exception as the inner exception
or …
The benefit of the last one (if applicable) is the consumer can catch MyCustomException if it’s interesting for special handling.