在软件开发过程中,程序异常是十分常见的,也就是我们常说的BUG,因此需要我们对不可预期的异常进行处理。
异常处理其实很简单,最开始我也就得很难,不用怕、真的挺简单的,真正理解了顶多也就一个try-catch语句和throw语句。
try-catch语句用法:
try{
语句块1 //可能引发异常的代码
}
catch(异常类型1 异常对象1){
语句块2 //异常处理
}
catch(异常类型2 异常对象2){
语句块3 //异常处理
}
当try语句块中有异常发生时,程序首先创建一个异常对象,然后依次搜索与之匹配的catch对象,如果找到了匹配的代码块,程序就会跳转到这个catch块并执行块中的语句。
下面给大家一个示例-阶乘的异常处理:
1、先给大家未做异常处理的代码:
截图我就不截了,当我们在输入框中输入的不是数字时系统就会产生异常,程序中断。这是最常见的输入异常。
2、下面是用try-catch语句把可能产生异常的语句写在try语句块中,在catch语句块中进行处理:
异常处理其实很简单,最开始我也就得很难,不用怕、真的挺简单的,真正理解了顶多也就一个try-catch语句和throw语句。
try-catch语句用法:
try{
语句块1 //可能引发异常的代码
}
catch(异常类型1 异常对象1){
语句块2 //异常处理
}
catch(异常类型2 异常对象2){
语句块3 //异常处理
}
当try语句块中有异常发生时,程序首先创建一个异常对象,然后依次搜索与之匹配的catch对象,如果找到了匹配的代码块,程序就会跳转到这个catch块并执行块中的语句。
下面给大家一个示例-阶乘的异常处理:
1、先给大家未做异常处理的代码:
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 Exception_test2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//计算阶乘的函数
public int Factorial(int n)
{
int result = 1, i = 1;
while (i <= n)
{
result *= i;
i++;
}
return result;
}
private void button1_Click(object sender, EventArgs e)
{
int n = Convert.ToInt32(textNum.Text);
int result = Factorial(n);
textRes.Text = result.ToString();
}
}
}
截图我就不截了,当我们在输入框中输入的不是数字时系统就会产生异常,程序中断。这是最常见的输入异常。
2、下面是用try-catch语句把可能产生异常的语句写在try语句块中,在catch语句块中进行处理:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public int Factorial(int n)
{
int result = 1, i = 1;
while (i <= n)
{
result *= i;
i++;
}
return result;
}
private void button1_Click(object sender, EventArgs e)
{
try
{
int n = Convert.ToInt32(textNum.Text);
int result = Factorial(n);
textRes.Text = result.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message,"输入格式错误!");
}
}
}
这下当我们在输入框中没有输入数字时就会弹出一个提示框说我格式输入不正确,这就是异常的处理。