tags:

views:

76

answers:

3

I know that general or "across the board" exception handling is a big no-no, however I believe that it is okay in this case.

Consider some custom wrapper around BinaryWriter/BinaryReader operations. (Yes, I know of .NET serialization) In all of the methods in this class, there would be the potential to have certain exceptions, like passing in a byte[] that is too short for the data you are trying to read out of it or attempting to read an incorrect type.

So there are all these different methods for writing/reading data and I would like to handle all instances of certain exceptions thrown in this class in a certain way. For example, returning an error state or setting a certain flag whenever an EndOfStreamException is thrown.

Is there a clean/good way to do this short of throwing a try/catch around each read/write operation? Or is this still a big no-no because users of the library should just try-catch the calls to the class themselves?

+2  A: 

You could wrap the BinaryWriter/Reader functions in your own object and catch the exceptions there.

Jon B
The binarywriter/reader functions are already in my own object. The problem is that there are many different functions (for different types of writes/reads) and I am attempting to get around try/catching each of those.
mphair
@mphair - if you have multiple functions that each call the multiple read/write functions, then you can't avoid this. If you have one function (like `Serialize()`) that calls lots of other functions, you can catch the exceptions there.
Jon B
@Jon B - Thanks.
mphair
+1  A: 

Leaving to the user/caller to handle the exception makes sense in some scenarios. What sort of things you plan to do when you catch the exceptions?

Can you split your code into a number of methods/functions? Each one should do a single thing so you'll have 1 or 2 try-catch block(s).

http://stackoverflow.com/questions/372282/exception-handling-in-c-multple-try-catches-vs-one

del.ave
+1  A: 

This has try/catch abuse written all over it. Any of the conditions you mention for which you need a catch are actually bugs in your program. You cannot fix a bug with a catch block, you can only hide the bug. The user is still going to be pretty miffed about it, she can't use her old data anymore. The end-result is the same whether you add a bunch of exception handling code or not: she's going to uninstall your update and send you a nasty email.

If for some reason it is acceptable that your update cannot read old data files anymore then tackle this at the root. Add, say, a version number to the data so you can easily detect that the file is no longer usable. No need to use an exception anymore. Or if it is easier to unwind the logic, you just need a single exception type. Leaving all other exceptions for which they were intended: "there's something really wrong here, let's not try to plod on".

Hans Passant