简体   繁体   English

C# 捕获异常

[英]C# Catch Exception

Which exception would I use in a try/catch to find out when the user has inputted data in the wrong format?我将在 try/catch 中使用哪个异常来查明用户何时以错误的格式输入数据?

Example:例子:

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

Thanks谢谢

Don't do this.不要这样做。 It's a misuse of exception handling.这是对异常处理的滥用。 What you are attempting to do is considered coding by exception , which is an anti-pattern .您尝试做的事情被认为是异常编码,这是一种反模式

An exception is exactly what it sounds like, an exception to the norm.例外正是它听起来的样子,是规范的例外 It's defined by something you either haven't accounted for, or simply can't account for through traditional validation.它是由您没有考虑的东西定义的,或者根本无法通过传统验证来解释。 In this situation, you can definitely account for a format issue ahead of time.在这种情况下,您绝对可以提前解决格式问题。 If you know there is a possiblity that the inputted data will be in the wrong format, check for this case first.如果您知道输入的数据有可能是错误的格式,请先检查这种情况。 eg例如

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

You should avoid using Exceptions as flow control.您应该避免使用异常作为流控制。

If you want a textbox to be an int, this is where int.TryParse() method comes in handy如果您希望文本框成为 int,这就是int.TryParse()方法派上用场的地方

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

You can go with Exception ex to catch all exceptions.您可以 go 与Exception ex捕获所有异常。 If you want to catch a more specific one, though, you'll need to look at the documentation for whatever functions you are using to check the validity of the input.但是,如果您想获取更具体的内容,则需要查看文档以了解您用于检查输入有效性的任何功能。 For example, of you use int.TryParse() , then you will want to catch FormatException among others (see: http://msdn.microsoft.com/en-us/library/b3h1hf19.aspx for more information).例如,如果您使用int.TryParse() ,那么您将希望捕获FormatException等(有关更多信息,请参阅: http://msdn.microsoft.com/en-us/library/b3h1hf19.aspx )。

You can create your own exception like ↓您可以创建自己的异常↓

public class FormatException : Exception

And In your source, it might be...在你的消息来源中,它可能是......

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

Then, In your catch...然后,在你的捕获中...

catch(FormatException fex)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM