There is a program for working with a database on a local computer. There is a Data access layer project and a client application. In this client application, I catch exceptions right in the button click handler, when calling methods from DAL. Is it right to do so? If not, how and where to do it right? What is the rule of good tone for catching exceptions? Leave good articles if there are such. Thanks in advance for your help.

UPD ------

By the way, in MVC, the exceptions associated with incorrect input data, for example, on a textbox, are correctly caught in the View?

    2 answers 2

    General tips:

    • Take out the logic (including exception handling) from event handlers to separate methods, in the handler leave only the method call (Separation of UI and logic, code reuse).
    • Do not catch all exceptions. Usually all we can do with an unknown exception is to write it to the log. Therefore, instead of catching exceptions in each method, it is better to make a common handler, for example, so Application.ThreadException is an event (for WinForms)
    • Handle expected exceptions. For example, when connecting to a database, it is possible that SQL Server is unavailable.

    Excellent article on CodeProject on exception handling (in English).

      It is necessary to catch to handle exceptions at the same level of abstraction where it occurs. On the other hand, if it is necessary to forward an exception above, then it needs to change the level of abstraction and make it more general, and then make the initial one as inner.

      In your case, it turns out that the presentation layer works with exceptions from the data level. For example, the MVC approach for this is done by controllers who are responsible for properly providing data to the view. In turn, models make special services, and these services already interact with the repository. So, access to the repository occurs through a common interface that declares what exceptions can occur. As soon as they occur, the controller catches them and packs them into exceptions at its level of abstraction.

      As for the articles, I will not tell you, but in general this is studied in the courses of Software Design, handling exceptions. I know that this is a really important question and it is worth asking at an early design stage.