How and where do we write a catch catch block to handle Exception

We use C # to develop a Windows application.

Our Windows application consists of three layers (UI, Business, and DataAccess). In the business layer, there are some publicly available (business methods) through which the user interface binds wilh business-level classes. These public methods also have some private methods for implementing the required functionality. At the DataAcess level, there are several methods that are called from the Business layer class.

In this situation, where should I try to catch? a) In the business layer Public methods b) In busy mode Private methods c) In DataAccess Layer methods d) In user interface methods from which the business method is called.

+4
source share
3 answers

You should only handle exceptions when you expect them, and want to do something specific. Otherwise, IMO, it's better to let them bubble up in layers so that you have a full stack trace. Even at the presentation level, I would be inclined to have errors occur (for example, switch to a friendly error screen) if this were not the exception that I specifically expected.

A general rule with exceptions is to check your inputs to avoid them, anticipate what you expect to receive, and allow everything else to be exceptional and cause an error. Errors and stack traces are good. They tell you that something is wrong and where it went wrong. If this layer burrows its errors, it becomes almost impossible to determine what went wrong.

+3
source

Exceptions are difficult.

You should catch only those that you expect, and those that you expect, should be caught at the level of abstraction, which knows about the task that it is trying to accomplish, and not about the lower one, which simply knows about a small part of the task.

For example, you have a function that saves temporary files. This function calls functions that, for example, generate a temporary file name, save the file, and then return the path to the temporary file.

If the file save function shows that you gave it a file name that already exists in the directory, then this function should not work with it. He does not know about naming temporary files. The function you call to save the temporary file should probably handle this - it knows about the file names, and knew that you could create a duplicate. This way you can create a new name and try again.

function new_temp_file: try: name = generate_temp_name () save_temp_file (name) return name catch ExistingNameError: return new_temp_file ()

If you understand this above, then higher levels of abstraction know too much about lower levels.

This is just a simple example, but I hope you get what I am saying so ambiguously: catch the exception where the exception should be detected.

0
source

You must use the catch try block in each location, at the risk of throwing an exception that needs to be changed.

-2
source

Source: https://habr.com/ru/post/1303894/


All Articles