What should the function return in the catch block?

  • 0
    Suppose there is a function `string foo () {}` that returns some data. but the function may drop. Therefore, there is a try-catch block inside it. Question. What is more correct to do in a catch block? After all, the compiler will not let you collect the function. the catch block must also have some kind of return.

    What is more correct to be?
    C# Rosalie Hendricks, Oct 24, 2019

  • 3 Answers
  • 0
    If the method can fail and it is not clear what it should return in this case, it is more correct not to catch the exception at all. The exception should be handled at the level where it is clear how to handle it.

    A more advanced option is to catch the exception, log the error, and throw it further in its raw form ( throw; ) or wrapped in a business-specific exception:
    try
    {
    return int.Parse(stringValue);
    }
    catch (FormatException ex)
    {
    Logger.Error(ex);
    throw new MyParserException($"Неверный формат числа {stringValue}", ex);
    }
    catch (OverflowException ex)
    {
    Logger.Error(ex);
    throw new MyParserException($"Выход за допустимый диапазон {stringValue}", ex);
    }
    .
    Anonymous

  • 0
    1) it is not necessary in the catch to do what the function should return:
    public static object Points(int a, int b)
    {
    int result = 0;
    try
    {
    //делаю что-то и падаю
    return result;
    }
    catch(Exception ex)
    {
    Console.WriteLine(ex.StackTrace); //выведи мне в Console описание ошибки
    }
    return result;
    }


    2) there is a joke called finally
    int result  = 0;
    try
    {
    throw new Exception();
    return result;
    }
    catch (Exception ex)
    {
    Console.WriteLine(ex.StackTrace);
    }
    finally
    {
    result = -1;
    }



    which will be executed in any case (including when the function crashes)

    What should the function return in a catch block?


    1) Information about the error
    catch (Exception ex)
    {
    Console.WriteLine(ex.StackTrace);
    }


    2) either assign the values ​​of the output object (in your case it is string .. judging by the example)
    catch 
    {
    string result = "Ошибка";
    }


    3) you can do both

    4) you can do nothing in catch (called "stub")
    catch {}

    and after it return what needs to be retuned
    Anonymous

  • 0
    In the Try block, you put potentially unsafe code. In the Catch block, you handle an abnormal situation, but you need to understand that the stack can be damaged. Usually, an abnormal situation is recorded in this block, or an exception is passed to a higher-level function by the throw statement. In the finality block, resources are cleaned up, and finality is called by the garbage collector at an unknown point in time.

    In this case, variations of try-catch or try-finality are possible
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!