Try It - Catch Return Strategy

When used try-catchin methods, if you want the application to continue even if errors occur, is it normal to return the default value as a return through the catch block and register an error for later viewing?

Example:

public static string GetNameById(int id)
{
    string name;
    try
    {
        //Connect to Db and get name - some error occured
    }
    catch(Exception ex)
    {
        Log(ex);
        name = String.Empty;
    }

    return name;
}

Example 2:

public static string GetIdByName(string name)
{
    int id;
    try
    {
        //Connect to Db and get id- some error occured
    }
    catch(Exception ex)
    {
        Log(ex);
        id = 0;
    }

    return id;
}

Is it possible to return any default value (depending on the type of method return ... ???) so that the application logic, which required the result from this method, does not fail and keeps going ....

Thanks in advance...

Sincerely.

+5
source share
11 answers

, , - (, , , ..). , - .

- - :

public static string GetNameById(int id)
{
    string name;
    try
    {
        //Connect to Db and get name - some error occured
    }
    catch(Exception ex)
    {
        Log(ex);
        throw; // Re-throw the exception, don't throw a new one...
    }

    return name;
}

, - .

, , , , , , , , , . " ", SO.com .

+6

, . , , . ( ).

TryGet, :

public static bool TryGetNameById(int id, out string name) 
{ 
    try 
    { 
         //Connect to Db and get name - some error occured
         name = actualName
         return true; 
    } 
    catch(Exception ex) 
    { 
        Log(ex); 
        name = String.Empty; 
        return false;
    }  
} 

, . , . -, , , -.

+4

: .

- , .

, , . , .

" " , CPU , .

, . , , .

- : PostSharp? , .

+2

, , . , , . / , .

, , , , , - , .

, , . - , / , .

+1

, , .

: "log the exception part", , ( ?)

, - swalowing, , .

0

. , , , , ...

catch, , , catch .

, , , "" , , , , , .

, , , , ...

0

, . , , , - - .

: , , .

0

try/catch , , .

. , , , .

, , , , / .

0

. : i, , , . Soemtiems . .

, " " , . (, ). , (T) maeks.

, 99% . 1% .

0

, " ".

. - , , .

. , , (, getSecurityGroup), , , , - , .

, , . - , , , ... .

, , , , , .

In fact, as a rule, at any time when you catch an error, you have to think a lot about whether the error is valid, and the continuation is valid or is it a stop show error, and you just have to refuse.

0
source

All Articles