【问题标题】:Try and catch, always catching exception尝试并捕捉,总是捕捉异常
【发布时间】:2024-01-13 07:08:02
【问题描述】:

我正在尝试做的是,从文本框中获取用户输入,将其转换为 int,然后使用它。我得到了一切工作,除了尝试和捕捉。万一这个人放了一个字母而不是一个数字。使用下面的代码,它总能捕捉到一些东西。我不知道是什么抓住了一些东西。我已经进行了布尔测试,如果我输入一封信,它只会抛出异常,然后发出哔哔声。其他然后等待有效输入。 请原谅我乱七八糟的代码,我仍然是初学者 C# 程序员:D 提前感谢!

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
    bool tone = false;
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        bool test = true;
        speedInput.Clear();
        beep.Clear();
        int beepspeed = 90;
        int speed = 100;
        string speedtext = this.speedInput.Text;
        string beeptext = this.beep.Text;
        try
        {
            test = true;
            beepspeed = Convert.ToInt32(beeptext);
            speed = Convert.ToInt32(speedtext);
        }
        catch (Exception)
        {
            MessageBox.Show("numbers above 37 only!!");
            test = false;
        }

        if (test)
        {
            for (int i = 0; i < beepspeed; i++)
            {
                if (this.tone)
                {
                    Random ran = new Random();
                    int rand = ran.Next(400, 3000);
                    Console.Beep(rand, speed);
                }
                else
                {
                    Console.Beep(1000, speed);
                }
            }
        }
    }

    private void radioButtonYes_CheckedChanged(object sender, EventArgs e)
    {
        this.tone = true;
    }

    private void radioButtonNo_CheckedChanged(object sender, EventArgs e)
    {
        this.tone = false;
    }
}
}

【问题讨论】:

  • 作为一个初学者,我会从打印异常开始。
  • 在 catch 块中放置一个断点,然后当它到达断点时,将鼠标放在单词 Exception 旁边的下划线上。您应该能够调出一些异常详细信息,消息和堆栈跟踪非常适合发布。

标签: c# visual-studio try-catch


【解决方案1】:

您正在清理 button1_click 开头的输入内容

speedInput.Clear();
beep.Clear();

然后,当您尝试将空字符串转换为 int32 时,它会失败

beepspeed = Convert.ToInt32(beeptext);
speed = Convert.ToInt32(speedtext);

【讨论】:

  • 特里·普拉切特 — '给一个人一把火,他会暖一整天,但放火烧他,他的余生都会暖和
  • 哇,我把它放进了一些测试,忘了它..然后它又回来咬我.. 哈哈,谢谢你的修复:)
  • @JimW,匿名 - '四只眼睛看到的不止两个' :)