格式异常,我做错了什么? [英] Format Exception, What Am I Doing Wrong?

查看:92
本文介绍了格式异常,我做错了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的应用程序,当有人输入信件或不是数字的某个信息时,会显示以下消息:您必须输入一个数字!

I want that my app, when someone enters a letter, or sometehing that isn't a number, shows this message: "You must enter a number!"

void Button_guessClick(object sender, EventArgs e)
{
    try
    {
        int guess = Convert.ToInt32(textBox_guess.Text);
    }
    catch(FormatException ex)
    {
    	MessageBox.Show("You must enter a number!");
    }

    if (guess > number)
    {
    	MessageBox.Show("The number is smaller!");
    }
    
    if (guess < number)
    {
    	MessageBox.Show("The number is bigger!");
    }
    
    if (guess == number)
    {
    	MessageBox.Show("Bravo, you have guessed it");
    	Application.Exit();
    }
}

推荐答案

我不清楚你出了什么问题,但我认为你的方法的基础是错误的...

你不应该使用try ... catch - 这是一个非常昂贵的写作...

使用Int32.TryParse [ ^ ]检查值是否为数字...
It's not exactly clear to me what went wrong with you, but I think that the base of your approach is wrong...
You should not use try...catch - it's a very expensive writing...
Do use Int32.TryParse[^] to check if the value is numeric...


为什么不正确执行,而不是使用exceptiosn作为正常操作处理的一部分?

Why not do it properly, instead of using exceptiosn as part of your "normal operation" processing?
int guess;

if (!int.TryParse(textbox_guess.Text, out guess))
   {
   MessageBox.Show("You must enter a number!");
   }
else
   {
   if (guess > number...





缩进还原 - OriginalGriff [/ edit]



[edit]Indentation reverted - OriginalGriff[/edit]


问题是在你得到异常之后你不存在这个函数。那么其他验证就会执行,你也会得到一些其他的消息。



problem is after you get exception you are not exist the function. then other validations will perform and you will get some other messages as well.

try{
int guess = Convert.ToInt32(textBox_guess.Text);
}

catch(FormatException ex){
    MessageBox.Show("You must enter a number!");
    return; // this will return from your function no more messages will show..
}





你最好使用 Int32.TryParse 作为其他答案指出。


这篇关于格式异常,我做错了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆