Home > Software engineering >  try multi catch vs try catch by if
try multi catch vs try catch by if

Time:08-15

iam trying to write code and see two Approach:

try
{
    ...
}
catch(Exception ex)
{
    if (ex is ObjectNotFoundException)
    {
        return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
    }

    if (ex is ModelValidationException)
    {
        return Request.CreateErrorResponse(HttpStatusCode.NotAcceptable, ex);
    }
}

and

try
{
   ...
}
catch (ObjectNotFoundException ex)
{
    return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
}
catch (ModelValidationException ex)
{
    return Request.CreateErrorResponse(HttpStatusCode.NotAcceptable, ex);
}

which is better in performance and in practice?

CodePudding user response:

The second approach is better since you don't want to swallow all other exceptions silently. But instead of letting the process to crash after getting uncaught exception types, it would be better to catch them, log error details and return an internal server error:

try
{
   // ...
}
catch (ObjectNotFoundException ex)
{
    return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
}
catch (ModelValidationException ex)
{
    return Request.CreateErrorResponse(HttpStatusCode.NotAcceptable, ex);
}
catch(Exception ex)
{
    // log this error, so you are notified about it
    return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
}

CodePudding user response:

The second approach is correct, catch specific exception types.

The first approach,

try
{
    ...
}
catch(Exception ex)
{
    if (ex is ObjectNotFoundException)
    {
        return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
    }

    if (ex is ModelValidationException)
    {
        return Request.CreateErrorResponse(HttpStatusCode.NotAcceptable, ex);
    }
}

is a bad idea, do not do this! It suppresses and discards unexpected exceptions.

You don't rethrow the exception if it doesn't match one of your if conditions. You could radically improve things by doing,

try
{
    ...
}
catch(Exception ex)
{
    ...
    throw;
}

However, if you want a catch block that catches specific types, use the conventional pattern. This is more likely to be understood and supported in the future and less likely to lead to unexpected bugs.


Additionally, I suspect the typed catches would have performance advantages as the built in type checking is likely optimized.

However, you would need to run benchmarks with a defined workload to validate that assumption.

  • Related