Best Practices for Catching Exceptions (C # /. Net)

If I have a code like this:

void a()
{
    try
    {
        b();
    }
    catch (MyException)
    {
        // Handle any problems that occurred in b(c(d()))
    }
}

void b()
{
    c();
    // Do something else
}

void c()
{
    d();
    // Do something else
}

void d()
{
    // Do something, throw a MyException if it fails
}

Assuming no cleanup is needed at any time, it is best to put try {} catch {throw;} around the call to d () in c () and the call to c () in b (), or he considered OK to exclude from d ( ) The bubble before () is "natural" without any intermediate try / catch blocks?

I believe the optional try / catch block acts as a kind of “documentation”, but they seem redundant, so I'm just wondering what other people consider the best.

Sorry if this is all too thorough, I’m trying to deal with exceptions, but I don’t have a good relationship with them yet.

+5
source share
4 answers

, . , . , , c()?

+13

, . .

, - ( ). , , - .

+3

, , - , , , & c.

, - . , , . : , , , ?

  • (, , WinForms ASP.NET , ).
  • , (, , , , WCF).
  • , .
  • .

. , . SqlExceptions (, YourApp.UnknownCustomer), .

: , , . , , , !; -)

+3

I would say it depends on what you want to do with the information.

I always try to catch problems as close to the source as possible - why solve all this with a problem, and not try to deal with it where it happens? For ease of reading and understanding the code, I also believe that try / catch is as close as possible to the source of the problem.

If you are writing a program for yourself, and no one else will touch it, do whatever is best for you and the code.

0
source

All Articles