.netexception

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.


Solution

  • 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
    }