使用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
”。在使用远程调用服务时,服务端的自定义异常要保证客户端也可用,客户端包括调用方和代理。
来源:oschina
链接:https://my.oschina.net/u/4351246/blog/4282595