C#中使用try-catch语句添加异常处理功能
1.设计一个Windows应用程序,在一个文本框中输入n个数字,中间用逗号做间隔,然后编程对数字排序并输出,效果如图所示。

2.按<F11>键启用逐语句方式跟踪每一条语句的执行情况,在调试过程中将a添加到监视窗口。注意,观察各数组元素的变化过程。
3.设置“ for(int i = 1; i <= a.Length; i++)”语句为断点,然后按<F5>键启用调试器,当程序中断运行时,将数据sources添加到监视窗口,观察各数组元素的值。
4.上述代码在用户不按规定输入数据时会发生异常,修改源代码,使用try-catch语句添加异常处理功能。
try
{
for (int i = 0; i < sources.Length; i++)
{
a[i] = Convert.ToInt32(sources[i]);
}
}catch(Exception ex)
{
label2.Text = ex.Message;
}
5.然后输入一下数据:“5.6.3.7.9.1.4.8”,单击“排序”按钮,注意观察异常信息,分析错误的原因。
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 作业7
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string[] sources = textBox1.Text.Split(',');
int[] a = new int[sources.Length];
try//copy from iotword.com
{
for (int i = 0; i < sources.Length; i++)
{
a[i] = Convert.ToInt32(sources[i]);
}
}//copy from iotword.com
catch (Exception ex)
{
label2.Text = ex.Message;
}
for (int i = 1; i <= a.Length; i++)
{
for (int j = 1; j <= a.Length - i; j++)
{
if (a[j - 1] > a[j])
{
int t = a[j - 1]; a[j - 1] = a[j]; a[j] = t;
}
}
}
foreach (int t in a)
{//copy from iotword.com
label2.Text += string.Format("{0,-4:D}", t);
}
}
}
}