2016-02-03 47 views
2

我正在寫一個簡單的應用程序,它將2個文本框的輸入作爲分子和分母,然後將它們傳遞給Reduce()方法。爲什麼2個Try/Catch塊會凍結應用程序?

我需要將文本框字符串轉換爲整數,但我不希望它停止程序,如果用戶意外鍵入非數字鍵,所以我把任務放在Try ... Catch語句中爲了防止這種情況發生。

但是,當我在2個文本框中鍵入字母並按下按鈕時,窗口就會凍結並且全部扭曲。任何人都可以解釋發生了什麼?

這是我的代碼:

Private Sub btnReduce_Click(ByVal sender As Object, 
      ByVal e As EventArgs) Handles btnReduce.Click 
    Dim n As Integer 
    Dim d As Integer 
    Try 
     n = Val(txtNum.Text) 
    Catch ex As Exception 
     MsgBox("Please enter a numeric numerator", , "ERROR") 
     Exit Sub 
    End Try 
    Try 
     d = Val(txtDenom.Text) 
    Catch ex As Exception 
     MsgBox("Please enter a numeric denominator", , "ERROR") 
     Exit Sub 
    End Try 
    Reduce(n, d) 
    Dim reduced As String = n.ToString + "/" + d.ToString 
    lblDisplay.Text = "The reduced fraction is " + reduced 
End Sub 
+0

非常感謝! :)過去幾個月你對我的幫助很大。 –

回答

6

Try/CatchVal使用Integer.TryParse(或其它類型)相反。問題是Val如果不好就不會拋出異常。這將返回值的任何領先的數字:

n = Val("abc")   ' == 0.0 
n = Val("1a2b3c")  ' == 1.0 

它也總是返回Double,所以下面:

Dim n As Integer 
n = Val(txtNum.Text) 

...是Option Strict下無效代碼 - 你想分配雙倍到一個整數。

Dim n As Integer 
Dim d As Integer 

' if it can parse a value, it will be stored in n 
If Integer.TryParse(txtNum.Text, n) = False Then 
    MsgBox("Please enter a numeric numerator", , "ERROR") 
    Exit Sub 
End If 

If Integer.TryParse(txtDenom.Text, d) = False Then 
    MsgBox("Please enter a numeric numerator", , "ERROR") 
    Exit Sub 
End If 

Reduce(n, d) 
... 

一到*.TryParse()的好處是,它避免例外通過返回Boolean。例外情況不適用於流程控制或數據驗證,這是您的代碼試圖使用它們的方式。

一般來說,最好避免像ValMid這些傳統的VB函數,而傾向於使用更好的類型,通常功能更強大,更靈活。

此外,打開Option Strict - 它會將許多運行時錯誤和令人毛骨悚然的錯誤轉換爲編譯器錯誤,並指出行/問題。例如,它可能實際上並沒有停留在該方法中,但後來在某處使用錯誤的值。

相關問題