开放的编程资料库

当前位置:我爱分享网 > C#教程 > 正文

C# 异常

在本文中,我们展示了如何在C#中使用IOExceptions。

使用IO经常会导致错误。.NET在发生IO错误时抛出IO异常。基本IO异常称为IOException

还有其他几个更具体的IO异常:

  • FileNotFoundException
  • DirectoryNotFoundException
  • DriveNotFoundException
  • PathTooLongException
  • OperationCanceledException

这些是从基础IOException派生的。在处理异常时,我们总是最后处理IOException。否则,将不会评估更具体的异常。

异常是用try/catch关键字处理的。我们程序的用户应该看到易于理解的错误消息。更多技术细节将保留给管理员。错误通常会写入日志文件。

读取文件

根据文档,File.ReadAllText方法打开一个文本文件,读取文件中的所有文本,然后关闭文件。文档还列出了可能抛出的异常。

var filename = "words.txt";

var content = File.ReadAllText(filename);
Console.WriteLine(content);

该示例读取文本文件的内容。如果未完成显式异常处理,.NET将处理异常。

$ dotnet run
Unhandled exception. System.IO.FileNotFoundException: Could not find file ...

由于文件丢失,程序失败并返回System.IO.FileNotFoundException

try/catch关键字

在下一个示例中,我们使用try/catch处理可能的错误。

var filename = "words.txt";

try
{
    var content = File.ReadAllText(filename);
    Console.WriteLine(content);
}
catch (FileNotFoundException e)
{
    Console.WriteLine("failed to read file");
    Console.WriteLine(e.Message);
}

异常处理的目标之一是向用户提供可访问的错误消息。他们不应该被例外的技术细节所困扰。

$ dotnet run
failed to read file
Could not find file '/home/jano/Documents/prog/csharp/ioex/First/words.txt'.

这次我们有一个更易读的错误消息。

var filename = "words.txt";

try
{
    var content = File.ReadAllText(filename);
    Console.WriteLine(content);
}
catch (FileNotFoundException e)
{
    Console.WriteLine("file was not found");
    Console.WriteLine(e.Message);
}
catch (IOException e)
{
    Console.WriteLine("IO error");
    Console.WriteLine(e.Message);
}

如果我们还捕获基本的IOException,它必须跟在更具体的异常之后。

网络流

当我们读写网络流时,会抛出IO异常。

using System.Text;
using System.Net.Sockets;

using var client = new TcpClient();

var hostname = "webcode.me";
client.Connect(hostname, 80);

using NetworkStream networkStream = client.GetStream();
networkStream.ReadTimeout = 2000;

var message = @"GET / HTTP/1.1
Accept: text/html, charset=utf-8
Accept-Language: en-US
User-Agent: C# program
Connection: close
Host: webcode.me" + "\r\n\r\n";

using var reader = new StreamReader(networkStream, Encoding.UTF8);
byte[] bytes = Encoding.UTF8.GetBytes(message);

try
{
    networkStream.Write(bytes, 0, bytes.Length);
    Console.WriteLine(reader.ReadToEnd());
}
catch (IOException e)
{
    Console.WriteLine("GET request failed");
    Console.WriteLine(e.Message);
}

该示例创建对网页的GET请求。

try
{
    networkStream.Write(bytes, 0, bytes.Length);
    Console.WriteLine(reader.ReadToEnd());
}
catch (IOException e)
{
    Console.WriteLine("GET request failed");
    Console.WriteLine(e.Message);
}

网络流WriteReadToEnd方法可能抛出IO异常。

在本文中,我们使用了C#中的IOExceptions。

列出所有C#教程。

未经允许不得转载:我爱分享网 » C# 异常

感觉很棒!可以赞赏支持我哟~

赞(0) 打赏