Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Practice for Try Catch Error Handling

I'm trying to avoid returning an incorrect value when in the catch but I'm having trouble finding a better solution than this:

    private SecurityLevel ApiGetSecurityLevel()
    {
        try
        {
            return _BioidInstance.GetSecurityLevel();
        }
        catch
        { 
            return SecurityLevel.High;
        }
    }

Is there a better way of doing this so I don't return incorrect values? I can't change the SecurityLevel enum.

like image 217
Robert Avatar asked Nov 28 '22 15:11

Robert


2 Answers

Do not catch the exception. Allow the exception to "bubble-up" to force the caller/callers to handle setting the default security value.


If you really want to return a value then use Nullable<SecurityLevel> or SecurityLevel?.

private SecurityLevel? ApiGetSecurityLevel() { 
    try { 
        return _BioidInstance.GetSecurityLevel(); 
    } 
    catch {  
        return null; 
    } 
} 

Then use as:

if (ApiGetSecurityLevel().HasValue == false) {
    // use default security level
}
like image 191
AMissico Avatar answered Dec 10 '22 09:12

AMissico


Is it possible this is a case where the application should just fail? That is, if the SecurityLevel can't be determined, the user shouldn't be able to continue?

If so, why no just re-throw and let the UI handle it (or let it get logged, however your shop works)?

If the application should be able to continue, pick (and document) some default value and do exactly what you're doing.

like image 42
AllenG Avatar answered Dec 10 '22 08:12

AllenG