I don’t have much experience with exceptions and I’m trying to figure out how to use exception handling correctly in real world scenarios. In C#.
In this example I have one top level function, LoadModel, that calls lot of other functions (that call other functions, …):
class Core
{
public void LoadModel(string file_name)
{
try
{
// call other functions (that call other functions, …) that may throw exceptions
}
catch (Exception ex)
{
if (ex is ArgumentNullException ||
ex is ArgumentException ||
ex is EncoderFallbackException ||
ex is InvalidOperationException ||
ex is XmlException ||
ex is InvalidDataException ||
ex is IOException)
{
// show error message
}
else
{
// unsupported exception. system may be unstable. let it crash.
throw;
}
}
}
}
I adhered to this rules:
- All functions report errors using exceptions, i.e. they don’t return error codes. It’s the same paradigm as in .NET framework.
- If you are inside some lower level function and exception occurs and it’s not appropriate to report the failure to the user at this place, don't catch the exception and let it propagate upwards the call stack.
- Don’t use empty catch to catch all exceptions at top level. It would hide problems with you app an could destabilize it. Catch only exceptions you know how to recover from.
Question: Is this how you handle exceptions? I.e. I check what exceptions my guarded code generates (considering also all nested functions), decide from which it’s safe to recover and put them into high level catch. I can get the list of exceptions for .NET functions from their documentation and for my own functions I should keep the list of exceptions in their documentation. And this exception list tends to accumulate: a function can throw its own exceptions and exceptions of its nested functions…….It seems error prone to me. Someone adds new exception in some nested function, and your top level catch won’t handle it. With error codes you could do something like "if (error != SUCCESS)" to catch all errors, but you can’t do it with exceptions (if you don’t want to use empty catch).