Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IOException vs. TimeoutException

Tags:

c#

.net

Assuming you design a System.IO.Stream extension MyStream whose Read method can time out, which exception type would you rather throw:

  • System.IO.IOException (as e.g. System.Net.Sockets.NetworkStream) or
  • System.TimeoutException (as e.g. System.IO.Ports.SerialPort) or
  • something else?
like image 446
tamberg Avatar asked May 13 '26 20:05

tamberg


2 Answers

If the exception is that the Stream is going to "time out", then I would personally use TimeoutException. This is very clear, and very appropriate if that is the underlying cause.

IOException is used by NetworkStream, but has a different meaning. In this case, it's typically because the underlying socket has closed, which prevents the read/write from occurring...

like image 102
Reed Copsey Avatar answered May 16 '26 11:05

Reed Copsey


You use a TimeoutException; it most accurately conveys what actually happened.

The IOException is more of a general-purpose exception; if something happened while reading the underlying backing store for the Stream for which there's not a specific exception then I'd expect an IOException.

TimeoutException is the standard here, so go with that.

like image 27
casperOne Avatar answered May 16 '26 12:05

casperOne