1

I have some text in a string which I'm reading in. The object which contains the string provides a method for me to extract the contents of the string and then throws an exception (EndOfStreamException) when the string is empty. At that point I'd like to finish my data extraction and continue with working on it. I'm not very certain how to do this. Here is what I am guessing.

while(/*some condition on the data*/)
try
{
    objWithString.ExtractData();
}
catch (Exception e)
{
    if(e is EndOfStreamException)
        {
            break;
        }
    else
       throw e;
}
}
4
  • You can just catch(EndOfStreamException e) instead of using the if block Commented Nov 29, 2011 at 5:06
  • I know, I didn't write this code and I'd never seen such code but it works. It's a small project. Commented Nov 29, 2011 at 5:10
  • See, if the objWithString has other methods. May be one of them may help you without throwing an exception. If it's some normal third party library, I'm sure there is a such functionality Commented Nov 29, 2011 at 5:13
  • 1
    Never write throw e;. Commented Nov 29, 2011 at 16:45

1 Answer 1

4

That will work, but it would be better to catch the specific exception than to do the test at runtime, ie.

while (/*some condition on the data*/)
try
{
    objWithString.ExtractData();
}
catch (EndOfStreamException)
{
    break;
}

I'm not entirely sure if "break" will work inside a catch clause. If not, you may have to extract this into a method and use "return".

Generally using exceptions for flow control is considered poor design, since exceptions are intended for "exceptional" conditions and reaching the end of the stream is normal and expected, not exceptional. Of course, if you have no control over the implementation of the stream then you have to go with this approach.

Sign up to request clarification or add additional context in comments.

1 Comment

Throwing and catching an exception is also quite expensive, performance-wise. This is another good reason why exceptions should not generally be thrown during the typical use case of a method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.