异常处理基础

一、使用try和catch进行异常处理 

在执行try语句中的代码时发生异常,程序流程将会立即跳转到catch语句,执行catch语句中的代码,而不是显示晦涩难懂的消息。

using System;

class MyError
{
    public static void Main()
    {
        int[] myArray = new int[5];

        try
        {
            for (int ctr = 0; ctr < 10; ctr++)
            {
                myArray[ctr] = ctr;//有问题的代码
                //Console.WriteLine(myArray[ctr]);
            }
        }

        catch
        {
            Console.WriteLine("The exception was caught!");
        }

        Console.WriteLine("At end of class");
        
    }
}

二、捕获异常信息

将异常作为参数传递进来。

using System;

class MyError
{
    public static void Main()
    {
        int[] myArray = new int[5];

        try
        {
            for (int ctr = 0; ctr < 10; ctr++)
            {
                myArray[ctr] = ctr;//有问题的代码
                //Console.WriteLine(myArray[ctr]);
            }
        }

        catch(Exception e)//将异常作为参数传递进来
        {
            Console.WriteLine("The exception was caught:\n{0}",e);//打印异常的具体内容
        }

        Console.WriteLine("At end of class");
        
    }
}

运行结果: 

 

三、 给try语句提供多个catch语句

使用更为具体的catch语句:

using System;

class MyError
{
    public static void Main()
    {
        int[] myArray = new int[5];

        try
        {
            for (int ctr = 0; ctr < 10; ctr++)
            {
                myArray[ctr] = ctr;//有问题的代码
            }
        }

        catch (IndexOutOfRangeException e)
        //IndexOutOfRangeException该异常类型专门用于索引超出范围的情况
        //因此catch语句将只捕获这种异常
        {
            Console.WriteLine("1111", e);
        }

        catch(Exception e)//将异常作为参数传递进来
        {
            Console.WriteLine("The exception was caught:\n{0}",e);
        }

        Console.WriteLine("222");
        
    }
}

运行结果:

 

四、使用关键字finally

finally语句块中的代码总是会执行。

using System;

class MyError
{
    public static void Main()
    {
        int[] myArray = new int[5];

        try
        {
            for (int ctr = 0; ctr < 10; ctr++)
            {
                myArray[ctr] = ctr;//有问题的代码
            }
        }

        catch(Exception e)//将异常作为参数传递进来
        {
            Console.WriteLine("The exception was caught:\n{0}",e);
        }

        finally
        {
            Console.WriteLine("333");
        }

        Console.WriteLine("222");
        
    }
}

运行结果: 

 

将catch代码块注释起来: 

using System;

class MyError
{
    public static void Main()
    {
        int[] myArray = new int[5];

        try
        {
            for (int ctr = 0; ctr < 10; ctr++)
            {
                myArray[ctr] = ctr;//有问题的代码
            }
        }

        //catch(Exception e)//将异常作为参数传递进来
        //{
        //    Console.WriteLine("The exception was caught:\n{0}",e);
        //}

        finally
        {
            Console.WriteLine("333");
        }

        Console.WriteLine("222");
        
    }
}

运行结果:

可以得出结论:finally代码块总是会执行。