我当前的作业让我使用try and catch
块进行错误处理。该代码应该计算超过500的值以输入特定值,并且在500以下计算不同的值。我的问题是我不知道把尝试和捕获处理线放在哪里。如果我在dueLbl.Text = "your payment is " & FormatCurrency(totalDue)
之后将try放在if语句和catch语句之上
我收到了endif must match if,else must precede if
,并且从未接触过。现在,如果我将try放在if语句之上并将catch留在最底部,代码将会运行但仍然不会捕获任何内容。
Public Class Form1
Private Sub calcButton_Click(sender As Object, e As EventArgs) Handles calcButton.Click
Dim kwHour As Double
Dim totalDue As Double
Dim basePay As Double
Dim overBasePay As Double
kwHour = kwhourValue.Text
If kwHour <= 500 Then
totalDue = kwHour * 0.27
dueLbl.Text = "your payment is " & FormatCurrency(totalDue)
Else
basePay = 500 * 0.27
overBasePay = (kwHour - 500) * 0.55
totalDue = basePay + overBasePay
dueLbl.Text = "your payment is " & FormatCurrency(totalDue)
End If
End Sub
End Class
答案 0 :(得分:0)
你可以这样做......
Private Sub calcButton_Click(sender As Object, e As EventArgs) Handles calcButton.Click
Try
Dim kwHour As Double
Dim totalDue As Double
Dim basePay As Double
Dim overBasePay As Double
kwHour = kwhourValue.Text
If kwHour <= 500 Then
totalDue = kwHour * 0.27
dueLbl.Text = "your payment is " & FormatCurrency(totalDue)
Else
basePay = 500 * 0.27
overBasePay = (kwHour - 500) * 0.55
totalDue = basePay + overBasePay
dueLbl.Text = "your payment is " & FormatCurrency(totalDue)
End If
Catch ex as Exception
MsgBox(ex.message)
Finally
'Whatever you want to do...
End Try
End Sub
您不能将Try Catch
语句放在IF
语句的中间。这不会正确结束您的IF
声明。上面的代码将捕获它在执行代码时遇到的任何错误。此外,您还可以添加Finally
。无论下面的代码是什么代码都会在遇到错误后执行。有点像结局代码:)
答案 1 :(得分:0)
当你说
时现在,如果我将try保留在if语句之上并将catch保留在最底层,代码将会运行但仍然无法捕获任何内容。
我猜你在
中收到了错误kwHour = kwhourValue.Text
所以你可以做的是将try语句放在try行块中包含该行的那一行之前。我在这里假设你被要求专门使用try catch块。否则,还有其他方法可以在这里做。你的任务到底是什么意思?
答案 2 :(得分:0)
通过这种方式......顺便说一句,您需要将kwhourValue.Text
转换为Double
Private Sub calcButton_Click(sender As Object, e As EventArgs) Handles calcButton.Click
Dim kwHour As Double
Dim totalDue As Double
Dim basePay As Double
Dim overBasePay As Double
Try
If Double.TryParse(kwhourValue.Text, kwHour) Then
' text is convertible to Double, and kwHour contains the Double value now
Else
' Cannot convert text to Double
End Sub
End If
If kwHour <= 500 Then
totalDue = kwHour * 0.27
dueLbl.Text = "your payment is " & FormatCurrency(totalDue)
Else
basePay = 500 * 0.27
overBasePay = (kwHour - 500) * 0.55
totalDue = basePay + overBasePay
dueLbl.Text = "your payment is " & FormatCurrency(totalDue)
End If
Catch ex as Exception
MsgBox(ex.message)
Finally
'Whatever you want to do...
End Try
End Sub