C # exception throwing

Suppose I have three functions doA (), doB () and doC () in a C # program, where I know that doA () will call doB (), which in turn will call doC ().

Since doC () needs to interact with the database, I know that it may well throw exceptions that it cannot decide what needs to be brought to the attention of the user. At the moment, I have some code that can cause an error in trying / catching in doC (), and then calling doC () in doB () in another try / catch and similarly calling doB () in doA () in a try block / catch. This allows me to simply use the cast; to throw an exception to doA (), where you can do something reasonable to display this to the user.

This is a bit like overkill. I am wondering if I do not plan to deal with the exception in doB () or doC (), if I can just get rid of the try / catch blocks there.

Assuming the blocks are ultimately not involved, what is the best practice for situations like this?

+3
source share
7 answers

If your catch blocks look like this:

catch (Exception)
{
    throw;
}

then they are meaningless. You cannot handle this exception - do not try to try / catch at all.

Personally, I have very few try / catch blocks in my code - and although there are many implicit try / finally blocks, most of them are associated with statements using.

+10
source

, try/catch - , . , throw;, , , :

catch (Exception exception)
{
    throw exception;
}
+5

, - ( ). , . , doA() (, , , , ) - , try/catch.

+5

.

, , , . , , .

: .

+2

IMHO, , .

, , , /, . , , - , -.

0

, - . , - - . - DoC(), .

catch ( , ), . , , .

, , , . , doC() , . - . .

0

The type of exceptions that you will catch may be different at each level, I'm not sure what you are doing at 3 levels, but at the top of the stack you can only have one type of exception, at the lower level there may be a different type of exception, which forces you use a broad type of exception, and then a specific one, which may not have clear information in it.

Thus, it depends on the types of exceptions that you will throw.

0
source

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


All Articles