Preserving the type of a re-thrown exception
.net, c#, exception
Solution
I would suggest not catching those exceptions at all...
The information you add could (mostly) be gleaned from the stackdump.
You could use catch-and-wrap to translate to a library-specific exception:
catch (Exception e)
{
throw new ReadStreamsErrorExecption(
String.Format("Exception occurred in stream {0}", i), e);
}
Problem
I am writing a class that does operations to multiple streams. Here is a example of what I am doing now ``` 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; ``` I would like to simplify my code down to ``` 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; ``` However if anyone is trying to catch specific exceptions my wrapper will hide the exception that Read threw. How can I preserve the type of exception, add my extra info, but not need to write a handler for every possible contingency in the try block.