jkb
jkb

Reputation: 1

correct exception handling in real world scenarios

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:

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).

Upvotes: 0

Views: 1217

Answers (1)

Rob G
Rob G

Reputation: 3526

You can catch multiple kinds of exceptions in a cascading manner:

try 
{

  //some code

}
catch (NonGenericException nonGenericEx) 
{

}
catch (MoreGenericException moreGenericEx) 
{

}
catch (Exception mostGenericException) 
{

} 
finally
{
  //this code will always be executed
}

Upvotes: 2

Related Questions