Hello. I never used exceptions, but now I decided to clarify this topic for myself. I found it pleasant to use exceptions, but here I also saw a warning against this. Imagine a case where we have a method such as user registration. This method hides in itself all the difficulties of registration, for example, verification of login and email. If the login is busy, the message should be displayed, the same with the email. The method itself is called from the asp.net controller.

public void RegisterUser(SignUpModel registerData) { if(!UserData.UserEmailIsFree(registerData.Email)) { throw new EmailIsNotFreeException(); } if(!UserData.UserLoginIsFree(registerData.Login)) { throw new LoginIsNotFreeException(); } User newUser = new User(); newUser.Login = registerData.Login; newUser.Password = registerData.Password; newUser.Email = registerData.Email; UserData.AddUser(newUser); } 

It would look like a code with exceptions. I understand this is a bad approach, but it's pretty darn convenient. In another case, return codes should be applied, as far as I understand. It turns out a vicious circle. Explain to me what to do? I need authoritative sources, code samples, elegant solutions and everything that you can help me. I understand that there are a lot of holivars on the Internet on this subject, but nowhere does it say which way to go without using exceptions. A lot of people say that exceptions are bad everywhere, but how to be then. I will be glad to each more or less useful answer. Thank!

    1 answer 1

    In short, I can advise you to set up agreements for the whole project on how errors will be handled, whether they will be indicated by return codes or exceptions, and follow this agreement uniformly, then you will not get confused when you are accompanied. It is worth noting, however, that exceptional situations should really be used in exceptional cases (ideally, they should be used for events that are very rare, or should never occur), because they at least break encapsulation: you can't just see which exceptions can "throw out" the code being called. In addition, they will have to be processed, otherwise the code will fall. In short, using them increases the complexity of the code.

    By the way, look at the bool Dictionary<TKey, TValue>.TryGetValue(TKey key, out TValue value) - a good example from the environment itself that you can do without exceptions.

    Finally, I advise you to read S. McConnell's "Perfect Code", Part II, Chapter 8 "Security Programming" - the questions asked are clearly and convincingly explained. Better yet, the whole book. :)

    • Thank you very much. Exhaustive answer. Especially pleased with the book. - Eriendel