VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > C#编程 >
  • C#教程之异常Exception(三)

本站最新发布   C#从入门到精通
试听地址  
https://www.xin3721.com/eschool/CSharpxin3721/

使用try...catch...捕获异常,如果能预料到某些异常可能发生,可以使用精确的异常例如“FileNotFoundException”、“DirectoryNotFoundException”、“IOException”等,最有使用一般异常“Exception”。

复制代码
using System;
using System.Collections;
using System.IO;

namespace ConsoleApp5
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                using (StreamReader sr = File.OpenText("data.txt"))
                {
                    Console.WriteLine($"The first line of this file is {sr.ReadLine()}");
                }
            }
            catch (FileNotFoundException e)
            {
                Console.WriteLine($"The file was not found: '{e}'");
            }
            catch (DirectoryNotFoundException e)
            {
                Console.WriteLine($"The directory was not found: '{e}'");
            }
            catch (IOException e)
            {
                Console.WriteLine($"The file could not be opened: '{e}'");
            }
            catch (Exception e)
            {
                Console.WriteLine($"其他异常:{e}");
            }
            Console.ReadLine();
        }    
    }
}
复制代码

使用throw,且throw添加异常对象,显示抛出异常。throw后面什么都不加,抛出当前异常。

复制代码
using System;
using System.IO;

namespace ConsoleApp5
{
    class Program
    {
        static void Main(string[] args)
        {
            FileStream fs=null;
            try
            {
                fs = new FileStream(@"C:\temp\data.txt", FileMode.Open);
                var sr = new StreamReader(fs);

                string line = sr.ReadLine();
                Console.WriteLine(line);
            }
            catch (FileNotFoundException e)
            {
                Console.WriteLine($"[Data File Missing] {e}");
                throw new FileNotFoundException(@"[data.txt not in c:\temp directory]", e);
                // 直接使用throw相当抛出当前异常。
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    Console.WriteLine("关掉");
                }
            }
            Console.ReadLine();
        }    
    }
}
复制代码

自定义异常:继承System.Exception。自定义的异常命名应该以“Exception”结尾,例如“StudentNotFoundException”。在使用远程调用服务时,服务端的自定义异常要保证客户端也可用,客户端包括调用方和代理。

有时候发生的异常导致后面的代码无法处理,如果后面的代码涉及到清理资源应当小心,这时应该在finally模块放入清理资源的代码。

 

量变会引起质变。
相关教程