簡體   English   中英

C# 捕獲異常

[英]C# Catch Exception

我將在 try/catch 中使用哪個異常來查明用戶何時以錯誤的格式輸入數據?

例子:

try
{
    string s = textBox1.Text;
    // User inputs an int
    // Input error
    MessageBox.Show(s);
}
catch(what exception)
{
    MessageBox.Show("Input in wrong format");
}

謝謝

不要這樣做。 這是對異常處理的濫用。 您嘗試做的事情被認為是異常編碼,這是一種反模式

例外正是它聽起來的樣子,是規范的例外 它是由您沒有考慮的東西定義的,或者根本無法通過傳統驗證來解釋。 在這種情況下,您絕對可以提前解決格式問題。 如果您知道輸入的數據有可能是錯誤的格式,請先檢查這種情況。 例如

if(!ValidateText(textBox1.text)) // Fake validation method, you'd create.
{
  // The input is wrong.
}
else
{
  // Normally process.
}

您應該避免使用異常作為流控制。

如果您希望文本框成為 int,這就是int.TryParse()方法派上用場的地方

int userInt;
if(!TryParse(textBox1.Text, out userInt)
{
    MessageBox.Show("Input in wrong format");
}

您可以 go 與Exception ex捕獲所有異常。 但是,如果您想獲取更具體的內容,則需要查看文檔以了解您用於檢查輸入有效性的任何功能。 例如,如果您使用int.TryParse() ,那么您將希望捕獲FormatException等(有關更多信息,請參閱: http://msdn.microsoft.com/en-us/library/b3h1hf19.aspx )。

您可以創建自己的異常↓

public class FormatException : Exception

在你的消息來源中,它可能是......

if (not int) throw new FormatException ("this is a int");

然后,在你的捕獲中...

catch(FormatException fex)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM