form1.cs

来自「Visual C#2005程序设计教程」· CS 代码 · 共 69 行

CS
69
字号
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace LT14_1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.Text = "捕获异常应用示例";
            label1.Text = "输入被除数";
            label2.Text = "输入除数";
            label3.Text = "";
            button1.Text = "计 算";
            button2.Text = "退 出";

        }

        private void button1_Click(object sender, EventArgs e)
        {
            int a, b , c;
            try    //试图捕获异常
            {
                a = Convert.ToInt32(textBox1.Text);   //将文本转换为Int32类型的整数
            }
            catch
            {   //发生异常时的处理
                label3 .Text ="提示:请将被除数的值输入为数字!";
                return;
            }
            try
            {
                b = Convert.ToInt32 (textBox2.Text);
            }
            catch
            {
                label3 .Text ="提示:请将除数的值输入为数字!";
                return;
            }
            try
            {
                c = a / b;
            }
            catch (DivideByZeroException)   //如果发生的异常为除数为0
            {
                label3 .Text ="提示:除数不能为0!";
                return;
            }
            
            label3.Text = "两数的商为:"+c.ToString();

        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?