C#异常处理(编辑中)

1 异常处理概述


    在C#编程中,我们可以通过异常处理语句对异常进行处理。我们经常使用到的异常处理语句有throw语句、try…catch语句和try…catch…finally语句。下面我们将对这些数据进行详细的说明。


2 异常处理方法


2.1 throw语句

    可以使用throw语句主动引发一个异常,也可以使用throw语句再次引发捕获的异常。好的编码做法是向再次引发的异常中添加更多信息以辅助调试。throw语法格式为

    throw ExObject // ExObject抛出的异常对象

【示例1】主动引发一个异常

    在下面的控制台应用程序中,我们定义了一个test类,在test类中我们定义了一个division的实现除法的方法,我们先判断分母的值是否为0,如果为0就同throw语句抛出异常。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace throw语句的应用演示
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("throw语句的应用---除法运算");
            Console.Write("输入第一个数:");
            double var1 = double.Parse(Console.ReadLine());
            Console.Write("输入第二个数:");
            double var2 = double.Parse(Console.ReadLine());
            Test te = new Test();
            te.Division(var1,var2);
            Console.ReadLine();
        }
    }
    class Test
    {
        public void Division(double var1, double var2)
        {
            if (var2==0)
            {
                //抛出System.DivideByZeroException异常
                throw new System.DivideByZeroException();
            }
            else
            {
                Console.WriteLine(var1+"/"+var2+"={0}", var1 / var2);
            }
        }
    }
}

输入数据与运行结果



【示例2】再次引发异常,添加更多调试信息

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

namespace throw语句的应用演示2
{
    class Program
    {
       static void Main(string[] args)
        {
            try
            {
                FileStream fs = new FileStream("data.txt", FileMode.Open);
                StreamReader sr = new StreamReader(fs);
                string line = sr.ReadLine();
                Console.WriteLine(line);
            }
            catch (FileNotFoundException e)
            {
                Console.WriteLine("[数据文件丢失]{0}",e);
                throw new FileNotFoundException("[没有找到data.txt文件]");
            }
        }
    }
}
运行结果



2.2 try…catch语句

    将可能引发异常的代码放在try块中,而将处理异常的代码放在catch块中。try…catch语法格式为

try

{

// 可能引发异常的代码

}

catch(异常类名  异常变量名)

{

// 用于处理异常的代码

}

【示例】在这个控制台应用程序中,我们先获取输入的值,然后将获取到的值使用Convert.ToInt32语句转换成整型。如果出现异常就会被catch捕获,然后输出异常信息。 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace try_catch使用演示
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("try_catch使用演示");
                Console.Write("请输入第一个数:");
                string var1 = Console.ReadLine();
                int var2 = Convert.ToInt32(var1);
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine("捕获到的异常:{0}", ex);
                Console.ReadLine();
            }
        }
    }

}

输入数据与运行结果



2.3 try…catch…finally语句

     将可能引发异常的语句放在try块中,将处理异常的语句放在catch块中,将必须总是执行的语句(如资源清理)放在finally块中的。finally总是执行,不论是否有异常发生。try…catch…finally语法格式为

try

{

// 可能出现异常的语句

}

catch(异常类名 变量名)

{

// 处理异常的语句

}

……

finally

{

// 总是执行的语句

}


【示例】

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace try_catch__finally语句的演示
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("try_catch__finally使用演示");
                Console.Write("请输入第一个数:");
                string var1 = Console.ReadLine();
                int var2 = Convert.ToInt32(var1);
                Console.WriteLine("输入的数为:{0}",var2);
            }
            catch (Exception ex)
            {
                Console.WriteLine("捕获到的异常:{0}", ex);
            }
            finally
            {
                Console.WriteLine("finally中的语句总是执行的");
                Console.ReadLine();
            }
        }
    }
}
输入数据与运行结果




3 自定义异常


    .NET框架提供从根基类Exception派生的异常类层次结构,这些类中的每一个都定义了一个特定的异常,因此在很多情况下只需捕获该异常。如果有特殊需要,我们也可以通过从ApplicationException类派生来创建自己的异常类。创建自己的异常类时,好的编码做法是在用户自定义的异常类名的结尾加上“Exception”这个词。

【示例】在下面的示例中,自定义异常类EmailException从System.ApplicationException派生,该类中定义了一个构造函数。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 自定义异常演示
{
    public class EmailException : ApplicationException
    {
        public EmailException(string message) : base(message) 
        { }
    }

    class Program
    {
        static void Main()
        {
            Console.WriteLine("请输入Email地址");
            string email = Console.ReadLine();
            string[] substrings = email.Split('@');
            try
            {
                if (substrings.Length != 2)
                {
                    throw new EmailException("email地址错误");
                }
                else
                {
                    Console.WriteLine("输入正确");
                }
            }
            catch (EmailException ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                Console.ReadLine();
            }
        }
    }

}

运行结果



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值