1

How would I convert this line from C++ to C#?

std::ifstream in;
in.exceptions(std::ios_base::badbit); //*THIS LINE*

According to this page, the previous line of code sets a new exception mask for the stream and clears any current error state flags. I'm also guessing that it is the "second form" of std::ios::exceptions from the page linked above.

Because of my inexperience with C#'s FileStream class, I've been getting pretty confused due to the lack of anything similar.

Eric after dark
  • 1,768
  • 4
  • 31
  • 79
  • For C++ only: streams throwing exceptions are bad (my opinion). For C++ interacting with c++/clr it becomes worse - you have to translate C++ exceptions to C++/clr exceptions, while crossing the boundary from C++ to C++/clr –  Mar 04 '15 at 20:12
  • Thanks for your response! I'm not using C++/clr. I just want to accomplish the same thing with C#. – Eric after dark Mar 04 '15 at 20:15
  • 1
    Are you trying to have FileStream throw exceptions on IO errors? Because that's the default behaviour. Both Read and Write methods will throw an IOException if an IO error occurs. – pixelbadger Mar 04 '15 at 20:43
  • I've expanded on my statement in an answer. If you found my comment useful, I would be grateful if you could mark this as the answer. – pixelbadger Mar 05 '15 at 10:46

1 Answers1

1

Both FileStream.Read and FileStream.Write methods will throw an IOException should any underlying I/O error occur. This is default behaviour.

Unlike C++, exception throwing is the expected form of error handling in C#. Because exceptions were a part of .NET from the beginning, there is none of the contention surrounding use of exceptions with streams as there is with C++.

Most - if not all - of the .NET framework standard libraries will throw exceptions in exceptional states. The only exception I can think of is when using the Try-Parse pattern, which is pretty explicit about the expected behaviour.

Community
  • 1
  • 1
pixelbadger
  • 1,556
  • 9
  • 24