问题描述
当我在文本框中输入一个空值时,我遇到了未处理的异常页面。当用户在文本框中输入空值时,我想显示一个错误消息框,我该怎么办?
namespace Random_çalışması
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Random rnd = new Random();
int number;
int answer;
private void button1_Click(object sender,EventArgs e)
{
number = rnd.Next(1,101);
label1.Text = number.ToString();
}
private void button2_Click(object sender,EventArgs e)
{
answer = Convert.ToInt32(textBox1.Text);
if(answer == number)
{
MessageBox.Show("Welcome to the page","Welcome!",MessageBoxButtons.OK,MessageBoxIcon.information);
}
else if(String.IsNullOrEmpty(textBox1.Text))
{
MessageBox.Show("Icorrect entrance","You can not acces to the page",MessageBoxIcon.Error);
}
else
{
MessageBox.Show("Icorrect entrance",MessageBoxIcon.Error);
}
}
}
解决方法
只需在方法的开头添加空测试:
int.TryParse()
您也可以使用Convert
代替TextChanged
来更好地捕获转换错误:。
How the int.TryParse actually works
您也可以简单地将按钮默认设置为禁用,并在private void textBox1_TextChanged(object sender,EventArgs e)
{
button.Enable = textBox1.Text != "";
}
事件上添加此处理程序:
int.TryParse
也可以在这里也private void textBox1_TextChanged(object sender,EventArgs e)
{
button.Enable = textBox1.Text != "" && int.TryParse(textBox1.Text,out _);
}
:
private void button2_Click(object sender,EventArgs e)
{
answer = Convert.ToInt32(textBox1.Text);
if ( answer == number )
MessageBox.Show("Welcome to the page","Welcome!",MessageBoxButtons.OK,MessageBoxIcon.Information);
else
MessageBox.Show("Icorrect entrance","You can not acces to the page",MessageBoxIcon.Error);
}
因此,仅当按钮不为空且不可转换且用户体验一致时才启用按钮。
现在按钮单击处理程序为:
import speech_recognition as sr
r = sr.Recognizer()
m = sr.Microphone()
try:
print("A moment of silence,please...")
with m as source: r.adjust_for_ambient_noise(source)
print("Set minimum energy threshold to {}".format(r.energy_threshold))
while True:
print("Say something!")
with m as source: audio = r.listen(source)
print("Got it! Now to recognize it...")
try:
value = r.recognize_google(audio)
if str is bytes:
print(u"You said {}".format(value).encode("utf-8"))
else:
print("You said {}".format(value))
except sr.UnknownValueError:
print("Oops! Didn't catch that")
except sr.RequestError as e:
print("Uh oh! Couldn't request results from Google Speech Recognition service; {0}".format(e))
except KeyboardInterrupt:
pass