There is a large module consisting of many methods. The module has an entry point - the initial method, which calls many other methods, which in turn cause something else and so on. All code in the initial method is wrapped in a try catch. Whether it is necessary to do any checks in the nested methods, if the initial method still catches the error. No special handling of all possible errors is required. In try catch it just logs it to the database. It just infuriates wildly in some of the nested methods to do something in the style:

if (City == null || City.House == null || City.House.Premise == null) throw new NullRefenceException("Какой-то текст для админа") DoSomething(City.House.Premise.Subscriber) 

either return null from this method, and in the calling method check the value for null and throw an exception there. I know that there is an operator "?.", But you cannot use new Sharpe pieces in our project. Therefore, the question has ripened: is it necessary to constantly do some checks, if there is a try catch in the initial method that will catch all exceptions and there will be only one code logging this error to the database. How to write? It is wildly boring for every sneeze to check something for null.

  • Exception trapping noticeably slows down the application. Because if execution speed is critical, it is better to avoid exception trapping. Definitely can not answer this question. - JaponDemon
  • I would say that catching exceptions just needs to be done in atomic methods, because they can later be used in other places. - yolosora

1 answer 1

There are guidelines with general recommendations when to throw an exception, and when not. In general terms, if a method can work out its logic - ok, if it can't - should throw an exception.

Also, if the method can be called only from your code, then the parameters should be already checked and they should not be checked a second time. If the parameters can come from the outside (from third-party code / file / methods that the consumer can overload / public methods of public classes / from somewhere else that you do not control), then they should be checked.