对于非法输入的处理

      这周的《软件测试技术》,我们又再次提起了“闰年问题”,至于如何判断闰年详见http://www.cnblogs.com/xlwm/p/4337150.html,在这里我们重点探讨下关于非法输入的问题。众所周知,在功能完备的软件里,应该全面地考虑到用户输入问题。而如果没有考虑,用户的非法输入可能会导致软件崩溃,甚至产生不可预料的后果。常见的处理方法,就是针对程序产生的exception进行try-catch,下面我们针对闰年问题来详细介绍:

一、问题描述:                                                        

通过输入年份,判断是否为闰年。

二、实现功能:                                                        

在文本框中输入年份,而后在窗口中点击“确定”按钮,弹出另一个窗口显示判断结果。

三、代码实现:                                                        

  这里是主要代码,我们从中可以看出int.parse函数是实现从string到int的转换,该函数可能会抛出异常,因为我们对此异常try-catch,在catch语句里进行非法输入的处理

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Drawing;
 6 using System.Linq;
 7 using System.Text;
 8 using System.Threading.Tasks;
 9 using System.Windows.Forms;
10 
11 namespace LeapYearTest
12 {
13     public partial class Form1 : Form
14     {
15         public Form1()
16         {
17             InitializeComponent();
18         }
19 
20         private void textBox1_TextChanged(object sender, EventArgs e)
21         {
22             
23         }
24 
25         private void button1_Click(object sender, EventArgs e)
26         {
27             Form2 form2 = new Form2();
28            try{
29             int year = int.Parse(textBox1.Text);
30             if (isLeapYear(year))
31                 form2.label1.Text = year+"年是闰年"; 
32             else
33                 form2.label1.Text = year+"年不是闰年";
34            }catch(Exception ex)
35            {
36                form2.label1.Text = "请输入合法年份";
37            }
38             form2.Show();
39             this.Hide();
40             
41         }
42 
43         private void Form1_Load(object sender, EventArgs e)
44         {
45         
46         }
47 
48         private void label1_Click(object sender, EventArgs e)
49         {
50 
51         }
52 
53         public static bool isLeapYear(int year)
54         {
55             if (year % 400 == 0)
56                 return true;
57             if (year % 100 == 0)
58                 return false;
59             if (year % 4 == 0)
60                 return true;
61             return false;
62 
63         }
64     }
65 }

 四、测试用例:                                                        

400 整除的年份

被 100 整除, 但是不被400 整除的年份

4 整除, 但是不被100 整除的年份

偶数, 不被4 整除的年份 奇数年份 其它非法输入的年份

五、测试结果:                                                       

(1)

                     

(2)

                   

(3)

                                  

(4)

                                 

(5)

                               

(6)

                           

(7)

                                  

六、可改进的地方:

      该程序乍看之下,已经处理了用户异常输入的问题,但是只要用户输入整数,比如0,-1,对于闰年的判断这也是有效的。事实上,目前世界通行的公历中,有持续时间为0的10天,即公元1582年10月5日至14日,而也正是从那时开始才慢慢有了”闰年“一说,因此这也可以作为判断闰年的一个限制条件。

原文地址:https://www.cnblogs.com/xlwm/p/4391930.html