2012-04-28 51 views
3

我正在執行一個存儲過程並返回一個字符串。該字符串設置爲根據條件返回10"USER DOES NOT EXISTS"嘗試抓住不好的編程練習

只是想知道以下是不好的編程習慣。

string result = _db.GetParameterValue(cmdObj, "@strMessage").ToString(); 
try 
{ 
    int a = int.Parse(result); 
    if (a == 1) 
     Console.WriteLine("A"); 
    else 
     Console.WriteLine("B"); 
} 
catch 
{ 
    Console.WriteLine(result); 
} 

Console.WriteLine(result); 

回答

4

你應該使用tryParse將其包括在try catch塊。

int outValue = -1; 
int.TryParse(result, out outValue); 
+0

是的,明白了。謝謝。 – Rain 2012-04-28 07:50:27

8

在捕獲失敗的int分析的基礎上,明確匹配總是比較好,而不是假定它是「USER NOT EXISTS」。

嘗試/抓住/吞下總是不好的做法。如果你要捕捉異常,請記錄它或扔掉。

你還沒有指定一種語言,所以假設它是C#,int.TryParse()int.Parse更清潔try/catch

+0

謝謝羅布裏奇。那是我想到的第二個想法。 – Rain 2012-04-28 07:48:46