C# 异常处理

        虽然早知道C#中"try……catch……finally……"的存在,但是一直没有用过,可能是潜意识里有“出现异常说明程序有bug啊不应该去debug吗要这个东西干嘛?”的想法吧,但是昨天才发现,总有些情况是你想象不到的QAQ,为了保证即是出现了异常还是能够正确的应对,这部分的语法还是很有用的。

    try……catch……finally是C#语言中包含的结构化异常处理语法,基本结构为

            try
            {

            }
            catch(<ExceptionType>)
            {

            }
            finally
            {

            }

    try后面的花括号里包含可能抛出异常的代码。

    catch可以指定Exception Type,只响应特定的异常,否则默认响应所有异常类型。

    finally是无论如何都会执行的代码,如果没有异常,就在try以后执行,如果出现异常,就在catch后执行。

    一个try……catch……finally中,结构是很灵活的:

    try+finally,

    try+catch,

    try+catch+finally,

    try+catch(Exception 1)+catch(Exception 2)+……,

    try+catch(Exception 1)+catch(Exception 2)+……+finally.

    另外,try……catch……finally是可以嵌套的。

    try……catch……finally的执行顺序是:

    如果try执行过程中没有异常,执行finally(如果存在)。

    如果try执行过程中出现异常,在发生异常处中断。

        如果有catch,逐个catch比对是否有和抛出异常匹配的。

            如果有和抛出的异常匹配的,执行对应的方法,然后执行finally(如果存在)。

            如果没有,执行finally(如果存在)。

        如果没有catch,执行finally(没有catch必须要有finally)。

在目前的测试任务中,遇到的问题是当测试系统出现异常,已测量的数据也没有正常记录,导致大量不必要的重复测试,浪费时间。下面是一个测试用的向ExceptionTest.txt文件写入数据的函数。当i=11时会超出数组大小,出现异常。

在不做异常处理的情况下,出现异常并中断后数据并没有成功写入文件。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;


namespace CSLearning
{
    public class ExceptrionLearning
    {
        public static void OutIndexExceptionTest()
        {
            string testpath = @"C:\Users\songmei1\Desktop\ExceptionTest.txt";
            StreamWriter mswriter = new StreamWriter(testpath, false, Encoding.UTF8);
            int[] testArray = new int[10];          
            for (int i = 0; i < 11; i++)
            {
                testArray[i] = i;                    
                mswriter.WriteLine(testArray[i].ToString());                    
            }
            mswriter.Close();
            mswriter.Dispose();
            mswriter = null;
        }
    }
}

加上异常处理结构后,无论是否出现异常,StreamWriter都会执行finally而正常关闭,数据也就成功写入。

            try
            {
                for (int i = 0; i < 11; i++)
                {
                    testArray[i] = i;                    
                    mswriter.WriteLine(testArray[i].ToString());                    
                }
            }
            catch(Exception)
            {
                mswriter.WriteLine("Exception occured!");
            }          
            finally
            {
                mswriter.Close();
                mswriter.Dispose();
                mswriter = null;
            }

    

猜你喜欢

转载自blog.csdn.net/u013004835/article/details/80190018