前言:


这个阶段我在学习设计模式,今天准备实战了,遇到了try……catch,在学C#的时候还记忆深刻呢?现在不懂得期中的道理了,温故知新,知识需要反复!今天,从实例中在温故一下Try……Catch,而顺道说说try……catch……finally 。


中心:


在C#中Try……Catch异常处理中,如果没有TRY,程序直接就会崩溃,如果没有Catch,异常总是向上层抛出或中断程序。 catch可以有多个,也可以没有,每个catch可以处理一个特定的异常。



(一)构造


<span style="font-size:18px;"><span style="font-size:18px;"><span style="font-size:18px;"><span >  </span>try
{
//有可能发生错误的程序块
}
catch (Exception)
{
//当发生错误的时候才会执行的代码块
throw;
} </span></span></span>


(二)实例中运用


<span style="font-size:18px;"><span style="font-size:18px;"><span style="font-size:18px;">using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace count
{
class Program
{
static void Main(string[] args)

{
try
{
Console.Write("请输入数字A:"); //显示请输入数字A:
string strNumberA = Console.ReadLine(); //获取用户输入的信息
Console.Write("请输入运算符(+、-、*、/):");//显示输入运算符
string strOperate = Console.ReadLine();//获取用户输入的预算符
Console.Write("请输入数字B:");//请输入数字B:
string strNumberB = Console.ReadLine();//请输入数字B:
string strResult = "";//运算结果
switch (strOperate )
{
case "+": //分支语句“+”运算
strResult = Convert.ToString(Convert.ToDouble
(strNumberA) + Convert.ToDouble(strNumberB));

break; //结束当前程序
case "-"://分支语句“-”运算
strResult = Convert.ToString(Convert.ToDouble
(strNumberA) - Convert.ToDouble(strNumberB));
break; //结束当前程序
case "*"://分支语句“*”运算
strResult = Convert.ToString(Convert.ToDouble
(strNumberA) * Convert.ToDouble(strNumberB));

break; //结束当前程序
case "/"://分支语句“/”运算
if (strNumberB != "0")//如果数字B不等于0
strResult = Convert.ToString(Convert.ToDouble //执行运算
(strNumberA) / Convert.ToDouble(strNumberB));
else //否则
strResult = "除数不能为0";//结果为“除数不能为0”
break; //结束当前程序

}
Console.WriteLine("结果是" + strResult);//显示结果
Console.ReadLine();

}
catch (Exception ex)//处理错误信息
{

Console.WriteLine("您的输入有错:" + ex.Message);//显示错误信息
}

}
}
}</span></span></span>

(三)运行结果

1.正常:                                                                       2.除数为0


【C#之Try……Catch实例】_实例

    

【C#之Try……Catch实例】_c#_02

【C#之Try……Catch实例】_trycatch_03

3.输入错误


(四)Try……Catch……finally(实际上finally可加可不加)


<span style="font-size:18px;"><span style="font-size:18px;"> try
{
//有可能发生错误的程序块
}
catch (Exception)
{
//当发生错误的时候才会执行的代码块
throw;
}
finally
{
//无论是否发生错误都会执行的代码块
}</span></span>

(五)在上面的实例中加入finally代码


<span style="font-size:18px;"><span style="font-size:18px;"> finally
{
Console.WriteLine("谢谢您的使用!欢迎下次光临!");
}</span></span>

运行效果:

【C#之Try……Catch实例】_trycatch_04






(六)补充


可加入下面代码,进行限度提示


<span style="font-size:18px;"><span style="font-size:18px;"><pre name="code" class="csharp">catch (IndexOutOfRangeException ex)
{
Console.WriteLine("Indexoutof异常:" + "不出现异常的限制" + ex.Message);
}</span></span>




总结:


  • 不要过多使用 catch。通常应允许异常在调用堆栈中往上传播。
  • 使用 try-finally 并避免将 try-catch 用于清理代码。在书写规范的异常代码中,try-finally 远比 try-catch 更为常用。

关于异常就介绍到这里,如果有问题,欢迎大家指正!