如何在C#中通过try/catch块为订单总价计算功能实现自定义格式错误提示
Hey there! Let's get that input validation sorted so your app tells users exactly which field they messed up. The issue with your current code is that Convert.ToInt32 will throw a FormatException if the input isn't a valid integer, and right now there's no handling for that—so your app might crash or behave unexpectedly.
Using Try/Catch Blocks for Per-Field Validation
We can wrap each input conversion in its own try/catch block. This way, we can catch the FormatException for each field individually and show a custom error message for the specific input that's wrong. We'll also clear out any old results/messages first to avoid confusion.
Here's your updated btnSubmit_Click method:
private void btnSubmit_Click(object sender, EventArgs e) { // Initialize variables with default values int Java = 0; int Latte = 0; int Mocha = 0; int Frappe = 0; string Name = txtName.Text; double javaPrice = 1.25; double mochaPrice = 2.95; double lattePrice = 2.75; double frappePrice = 3.25; double dblTaxRate = .09; double dblSubtotal; double dblTax; double dblTotal; // Clear previous messages and results txtMessage.Text = ""; txtSubtotal.Text = ""; txtTax.Text = ""; txtTotal.Text = ""; // Validate Java input try { Java = Convert.ToInt32(txtJava.Text); } catch (FormatException) { txtMessage.Text = "Please enter an integer for Java"; return; // Exit the method early since input is invalid } // Validate Latte input try { Latte = Convert.ToInt32(txtLatte.Text); } catch (FormatException) { txtMessage.Text = "Please enter an integer for Latte"; return; } // Validate Mocha input try { Mocha = Convert.ToInt32(txtMocha.Text); } catch (FormatException) { txtMessage.Text = "Please enter an integer for Mocha"; return; } // Validate Frappe input try { Frappe = Convert.ToInt32(txtFrappe.Text); } catch (FormatException) { txtMessage.Text = "Please enter an integer for Frappe"; return; } // All inputs are valid—calculate and display results dblSubtotal = Java * javaPrice + Mocha * mochaPrice + Frappe * frappePrice + Latte * lattePrice; dblTax = dblSubtotal * dblTaxRate; dblTotal = dblSubtotal + dblTax; txtMessage.Text = $"Thank you {Name} for your order!"; txtSubtotal.Text = dblSubtotal.ToString("C2"); txtTax.Text = dblTax.ToString("C2"); txtTotal.Text = dblTotal.ToString("C2"); }
How This Works:
- We start by clearing any existing text in the message and result fields so users don't see old data mixed with new errors.
- Each input field's conversion is wrapped in a separate
tryblock. If the conversion fails (e.g., user enters "abc" instead of a number), thecatchblock catches theFormatException, displays the custom error message, and exits the method withreturn—so no further calculations happen with invalid data. - If all conversions succeed, we proceed to calculate the subtotal, tax, and total, then display the success message and results.
A More Efficient Alternative: int.TryParse
While try/catch works, using int.TryParse is generally more efficient because exceptions have a performance cost. This method returns a boolean indicating whether the conversion succeeded, and outputs the parsed integer to a variable. Here's how you could rewrite the validation part with this approach:
// Validate Java input if (!int.TryParse(txtJava.Text, out Java)) { txtMessage.Text = "Please enter an integer for Java"; return; } // Validate Latte input if (!int.TryParse(txtLatte.Text, out Latte)) { txtMessage.Text = "Please enter an integer for Latte"; return; } // Repeat the same pattern for Mocha and Frappe...
This achieves the exact same result as the try/catch version but is lighter on resources, especially if users frequently enter invalid data.
内容的提问来源于stack exchange,提问作者BilboSwaggins

