首页 > 其他 > 详细

异常Exception(三)

时间:2020-05-17 19:27:37      阅读:50      评论:0      收藏:0      [点我收藏+]

上一篇:异常Exception(二)

使用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();
        }    
    }
}
View Code

使用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();
        }    
    }
}
View Code

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

 

异常Exception(三)

原文:https://www.cnblogs.com/bibi-feiniaoyuan/p/exception3.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!