Общая обработка исключений в C#

Понимание, когда абстракция среди утечек поставщиков Linq. Некоторые вещи работают над объектами, но не SQL (например.TakeWhile). Некоторые методы могут быть переведены в SQL (ToUpper), в то время как другие не могут. Некоторые методы более эффективны в объектах, где другие являются более эффективными при SQL (различные методы соединения).

7
задан Groo 27 October 2009 в 10:49
поделиться

8 ответов

I agree with FxCop and most of the other answers here: don't catch System.Exception ever, unless it is at the highest level in your application to log unexpected (and thus fatal) exceptions and then bomb the application. Also check out this question that's basically about the same thing.

Some other valid exceptions might be:

  • To catch exceptions for the sole reason of rethrowing a more descriptive one.
  • In unit test code that needs something more complex than an ExpectedExceptionAttribute.
  • In facade library code that only exists to shield callers from intricacies of calling some external (web) service, while never actually failing itself, no matter how badly the external system might go down.
6
ответ дан 6 December 2019 в 06:24
поделиться

I agree with the other answers that catch (Exception ex) is fine if you either

  1. just log and rethrow the exception or
  2. do it at the highest level (UI) of your application.

There is one more situation that comes to my mind where it could make sense: When writing unattended code (e.g. some system service), it can make perfect sense to keep the program running if some (well-defined) sub-task fails for whatever reason. Of course, care must be taken to ensure that the reason for the problem gets logged and (maybe) the task is tried again after some time.

5
ответ дан 6 December 2019 в 06:24
поделиться

Grey area...

In an ideal world you'd alway catch an explicit exception because, in theory, those are the only kind you can sensibly deal with - anything else should percolate through to some top level handler.

The trouble is we don't necessarily live in an ideal world and may well want to use a generic handler to accumulate additional information about the generic exception (parameters etc) into the exception and/or to perform additional logging before passing the exception back up the tree and in any case - at the appropriate level - to so arrange things that our end users don't see raw exceptions in the UI. The counter to this would be to suggest that when new errors occur at a low level (rather than arriving at your app level handler) you then add exception specific handling that can do your capture for you - but there can be deployment issues with this as a solution where including a generic case in bits of code that are, for whatever reason, a bit more prone to unhandled exceptions that one might like.

If it were me I'd probably be considering the flag on an assembly by assembly basis...

p.s. I'm assuming that at no point to you have a handler that just swallows the exception and allows the app to carry on.

4
ответ дан 6 December 2019 в 06:24
поделиться

Если вы пишете библиотеку (фреймворк), то FxCop на 100% прав.

Вы ловите исключения - что это значит? что вы знаете, почему они бросили. Вы уверены, что знаете все возможные причины?

Если вы пишете просто приложение, возможны варианты. Например, если вы перехватываете все необработанные исключения для ведения журнала.

4
ответ дан 6 December 2019 в 06:24
поделиться

Предполагается, что вы должны принимать исключения, которые вы умеете обрабатывать. Поймать исключение, а не выбросить его (напрямую или заключить в конкретное исключение) означает, что вы знаете специфику исключения в контексте приложения. Поскольку исключение может быть чем угодно, маловероятно, что вы знаете, как с ним бороться.

Если вы просто регистрируете исключение, в этом нет ничего страшного, просто зарегистрируйте его и отправьте внешнему слою для обработки или перехвата.

3
ответ дан 6 December 2019 в 06:24
поделиться

What does FxCopy say the specific violation is? If you want to just log information about an exception then rethrow it then this is perfectly valid, though there are other ways this might be done. If you are re-raising it though, make sure you just use:

 throw;

and not

 throw ex;

Maybe that's the issue?

2
ответ дан 6 December 2019 в 06:24
поделиться

Вы должны перехватывать только исключения, с которыми вы можете что-то сделать. В противном случае пусть исключение распространяется до вызывающего абонента или, например, в приложении Gui исключения должны обрабатываться общим обработчиком catch all, а затем регистрироваться. См .: UnhandledException Так что не ловите, если вы не собирались что-то с этим делать ... по общему признанию, это могло быть просто записью ошибки.

Edit Также посмотрите Application.ThreadException

2
ответ дан 6 December 2019 в 06:24
поделиться

If the code in the block should only throw an IOException, then why do you want to catch System.Exception as well?

Then, the degree of conformancy to FxCop guidelines you want to achieve is a choice of yours. I would see nothing bad in catching every exception at the highest possible level and log all the information you can, for example.

2
ответ дан 6 December 2019 в 06:24
поделиться
Другие вопросы по тегам:

Похожие вопросы: