【发布时间】:2020-08-30 10:33:00
【问题描述】:
我对 C# 很陌生。 我目前正在编写一个 WebSocket 应用程序,我需要在客户端断开连接时处理 NullReferenceException,因为我一直在从 ClientSocket 读取数据。
所以问题是: 当我将第二个 try-catch 块放在第一个块中时,我能够捕获 NullReferenceException。 但是当我删除嵌套的 try-catch 并尝试捕获提到的异常时,它会直接进入“finally”块。
try
{
using StreamReader streamReader = new StreamReader(stream);
while (true)
{
try
{
command = streamReader.ReadLine().Trim();
}
catch (NullReferenceException)
{
blah-blah
break;
}
}
}
//I place the NullReferenceException when removing the nested try-catch
catch (Exception e)
{
blah-blah
}
finally
{
blah-blah
}
【问题讨论】:
-
NullReferenceException在这里是完全可以避免的,因此内部的try/catch也是如此。 总是检查ReadLine的返回值是否为null。它does so at the end of input,这不是一个例外情况,而在null上调用一个方法是。
标签: c# exception nullpointerexception try-catch try-catch-finally