天天看点

Nearth===018/c#简易计算器求和异常处理

计算器求和异常处理代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
//此计算器只是简单实现了两个数的加减乘除,每一个功能代码都差不多,
//如果你看懂了加法块代码,那么其他的功能代码块也相应的明白
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)//求和
        {
            string add1 = textBox1.Text;
            string add2 = textBox2.Text;
            float number1 = 0;
            float number2 = 0;
            float sum=0;
            try
            {
                number1 = Single.Parse(add1);
            }
            catch(Exception e1) {
                MessageBox.Show("第一个加数异常",e1.Message);
                return;
            }
            try
            {
                number2 = Single.Parse(add2);
            }
            catch (Exception e2)
            {
                MessageBox.Show("第二个加数异常",e2.Message); 
                return;

            } 
            sum = number1 + number2;
            textBox3.Text = sum.ToString();
        }
    }
}      
运行结果:

你总说很累,可以后你还想再继续累吗?

继续阅读