Mo920192
Mo920192

Reputation: 39

C# Try Catch not working. Wanting an error message to display when characters appear

I am trying to get a try-catch to work. I have made a website and part of it is to withdraw cash. When I put characters in the withdraw text box the display text is: "Transaction Completed - take your money."

This is my code. I am a beginner programmer and I do not know what to do. Variables that have not been explicitly declared in this code have been declared globally.

protected void continue_btn_Click(object sender, EventArgs e)
{

    // if the input of amount is not empty assign amount  to a conversion integer of txtAmount.Text
    if (txtAmount.Text != "")
    {
        try
        {
            amount = Convert.ToInt32(txtAmount.Text);
            hBos.setWithdrawls(amount);

        }

        catch (Exception ex)
        {
            resultLbl.Text = ex.Message;
        }
    }

    //if a radio button has been selected convert the selected amount and assign it to the amount variable
    else
    {
        amount = Convert.ToInt32(amountRadioBtnList.SelectedValue);
    }

    //if amount is not a multiple of 10 display an error message
    if (amount % 10 != 0)
    {
        resultLbl.Text = "Error- amount must be a multiple of 10";
        return;
    }


    else
    {
        //if euro is selected convert to euro with exchange rate
        if (currencyRadioBtnList.SelectedValue == "Euro")
        {
            decimalAmount = amount / hBos.getExchangeRate();
        }
        //decimal amount is equal to amount
        else
        {
            decimalAmount = amount;
        }
    }

    //if decimalAmount is greater than 250 
    //Displays error message
    if (decimalAmount > 250)
    {
        resultLbl.Text = "Error - cannot withdraw more than £250";
        return;
    }
    //invoke withdraw method using login. pin and decimal amount as parameters
    success = hBos.withdraw(login, pin, decimalAmount);

    //if the withdraw fails
    //Displays error message
    if (success == false)
    {
        resultLbl.Text ="Error - Insufficient funds";
    }

    //display message that transaction is sucessful
    else
    {
        resultLbl.Text = "Transaction Completed - take your money";
    }

    //if the print receipt check box has been checked 
    // save withdrawl to decimal amount
    //Then go to withdrawl reciept webpage
    if(checkPrintedRecipt.Checked == true)
    {
        Session["withdrawl"] = decimalAmount;
        Response.Redirect("WithdrawlReceipt");
    }


}

Upvotes: 0

Views: 2252

Answers (2)

Mahmood Shahrokni
Mahmood Shahrokni

Reputation: 236

Regardless of what you are doing in the rest of your code, your first if statement is ignored so the try-catch block is never observed. The reason is that you have put some characters in your text box although your if block checks empty input!

When I put characters in the withdraw textbox the diplay text is: Transaction Completed - take your money.

I think you were trying to code something like this :

if (txtAmount != null)
    {
    // try-catch block
    }

This statement can be reasonable because it shows that you want to prevent the possible nullreferenceexception. The structre tha you have used here is a kind of contradiction

Upvotes: 0

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239724

If you want to see the exception message, add a return after you set it:

// if the input of amount is not empty assign amount  to a conversion integer of txtAmount.Text
if (txtAmount.Text != "")
{
    try
    {
        amount = Convert.ToInt32(txtAmount.Text);
        hBos.setWithdrawls(amount);

    }

    catch (Exception ex)
    {
        resultLbl.Text = ex.Message;
        return;
    }
}

Much as you already have for some other failure conditions. At the moment, your catch sets a message but the method then continues. And then it attempts to withdraw 0 and succeeds.

There are a few other issues with this code - amount and decimalAmount are apparently fields rather than local variables. That fact is hiding the fact that there appear to be control flow paths in this logic that fail to set decimalAmount to anything sensible and so the code will use whatever value was left over from previous usage. Prefer to declare your variables as close as possible to where they're used (use locals rather than fields, declare them inside the smallest block where they're needed) to uncover those types of errors.

Also, rather than Convert.ToInt32 inside a try/catch block, you might want to consider int.TryParse instead. That's a method that expects parsing to possibly fail and allows you to cope with that gracefully rather than having to throw and catch an exception.

Upvotes: 1

Related Questions