Home > Mobile >  Is there a way to return a value from a try-catch block into a preexisting variable outside of the b
Is there a way to return a value from a try-catch block into a preexisting variable outside of the b

Time:02-27

I feel like this may be somewhat of a dumb question, but I've tried everything I currently know to do as a beginner of C# on this. Is there any way I can return a value into one I've already set to use elsewhere? Or am I just over-complicating this whole thing? Every time I try to set the already existing variable with one inside the curly brackets I get an error. Code I used below.

static double GetAmount()
{
    double amount;
    try
    {
        Console.WriteLine("Enter in the amount for the transaction: ");
        double amount1 = Convert.ToDouble(Console.ReadLine());
        return amount1;
    }
    catch (Exception ex)
    {
        bool f = true;
        Console.WriteLine(ex.Message);
        while (f == true)
            try
            {
                Console.WriteLine("Enter the total in a proper format, no letters or spaces please. ");
                double amount1 = Convert.ToDouble(Console.ReadLine());
                f = false;
                return amount1;
            }
            catch (Exception ex2)
            {
                Console.WriteLine(ex2.Message);
                Console.WriteLine("Please try again.");
            }
    }
    finally
    {
        return amount;
    }
    return amount;
}

CodePudding user response:

Olivier has explained your errors and warning well, i just want to add a different way to ask the user for the double amount. Always use TryParse if you handle input:

static double GetAmount()
{
    double? amount = null;
    while (!amount.HasValue) 
        amount = AskForAmount();
    return amount.Value;

    double? AskForAmount()
    {
        Console.WriteLine("Enter in the amount for the transaction: ");
        return Double.TryParse(Console.ReadLine(), out double value) ? value : null;
    }
}

CodePudding user response:

You get two compilations errors and a warning. To understand them you must know that the finally-block is always executed before returning from the try- or catch-block. I.e., return amount1; would execute the statement in finally-block return amount;. But only one return-statement can be executed. Therefore, you get the message:

CS0157 Control cannot leave the body of a finally clause

and

CS0165 Use of unassigned local variable 'amount'

because the variable is declared but is not assigned a value yet when return is called.

Also, you get the warning

CS0162 Unreachable code detected

on the last code line, because the method will either be left by one of the previous return-statements or stay in the while-loop forever. Therefore, this last return statement can never be executed.


The bool flag f is redundant. There is no point in setting it to true before the return statement since the method is exited at the return-statement. This terminates the while-loop at the same time. If you want to exit the loop without returning, you can call break;.

Simplified version using try-catch:

static double GetAmount()
{
    Console.Write("Enter in the amount for the transaction: ");
    while (true) {
        try {
            double amount = Convert.ToDouble(Console.ReadLine());
            return amount;
        } catch (Exception ex) {
            Console.WriteLine(ex.Message);
            Console.Write("Enter the total in a proper format, no letters or spaces please: ");
        }
    }
}

The statement while (true) introduces an endless loop. Endless unless it is left by return, break or an unhandled exception (or the frowned upon goto command).

A better alternative is to use the TryParse method that does not throw an exception

static double GetAmount()
{
    Console.Write("Enter the amount for the transaction: ");
    while (true) {
        if (Double.TryParse(Console.ReadLine(), out double amount)) {
            return amount;
        }
        Console.Write("Enter the total in a proper format: ");
    }
}

This version has the same functionality as yours, is safe, is 3 times smaller and is much easier to read.

See also: try-finally (C# Reference)

CodePudding user response:

    static double GetAmount()
    {
        double amount = 0;
        try
        {
            Console.WriteLine("Enter in the amount for the transaction: ");
            amount = Convert.ToDouble(Console.ReadLine());
        }
        catch (Exception ex)
        {
            bool f = true;
            Console.WriteLine(ex.Message);
            while (f)
                try
                {
                    Console.WriteLine("Enter the total in a proper format, no letters or spaces please. ");
                    amount = Convert.ToDouble(Console.ReadLine());
                    f = false;
                }
                catch (Exception ex2)
                {
                    Console.WriteLine(ex2.Message);
                    Console.WriteLine("Please try again.");
                }
        }
        return amount;
    }
  • Related