gpt4 book ai didi

c# - 保留重新抛出的异常的类型

转载 作者:太空狗 更新时间:2023-10-30 00:46:46 26 4
gpt4 key购买 nike

我正在编写一个对多个流进行操作的类。这是我现在正在做的一个例子

Dictionary<int, int> dict = new Dictionary<int, int>(_Streams.Count);
for (int i = 0; i < _Streams.Count; i++)
{
try
{
dict.Add(i, _Streams[i].Read(buffer, offset, count));
}
catch (System.IO.IOException e)
{
throw new System.IO.IOException(String.Format("I/O exception occurred in stream {0}", i), e);
}
catch (System.NotSupportedException e)
{
throw new System.NotSupportedException(String.Format("The reading of the stream {0} is not supported", i), e);
}
catch (System.ObjectDisposedException e)
{
throw new System.ObjectDisposedException(String.Format("Stream {0} is Disposed", i), e);
}
}
int? last = null;
foreach (var i in dict)
{
if (last == null)
last = i.Value;
if (last != i.Value)
throw new ReadStreamsDiffrentExecption(dict);
last = i.Value;
}
return (int)last;

我想将我的代码简化为

Dictionary<int, int> dict = new Dictionary<int, int>(_Streams.Count);
for (int i = 0; i < _Streams.Count; i++)
{
try
{
dict.Add(i, _Streams[i].Read(buffer, offset, count));
}
catch (Exception e)
{
throw new Exception(String.Format("Exception occurred in stream {0}", i), e);
}
}
int? last = null;
foreach (var i in dict)
{
if (last == null)
last = i.Value;
if (last != i.Value)
throw new ReadStreamsDiffrentExecption(dict);
last = i.Value;
}
return (int)last;

但是,如果有人试图捕获特定的异常,我的包装器将隐藏 Read 抛出的异常。我怎样才能保留异常类型,添加我的额外信息,但不需要为 try block 中的每个可能的意外事件编写处理程序。

最佳答案

我建议不要完全捕获这些异常...

您添加的信息(大部分)可以从堆栈转储中收集。

您可以使用 catch-and-wrap 转换为特定于库的异常:

 catch (Exception e)
{
throw new ReadStreamsErrorExecption(
String.Format("Exception occurred in stream {0}", i), e);
}

关于c# - 保留重新抛出的异常的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2364988/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com