简体   繁体   中英

Is there a way to catch all exceptions of a certain type in a static class in C#?

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?

您可以将BinaryWriter / Reader函数包装在您自己的对象中,并在那里捕获异常。

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).

Exception Handling in C#: Multple Try/Catches vs. One

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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM