Try Catch Finally

G

Guest

Wht is the general prctise for having try catch block and Finally.

I mean in one methods what are Cicrustances to have entire code in ONE try
catch block or MULTIPLE and which lines of code is not required /suppose to
be in TRY blocks.
Thanking you in advance
 
B

Barry Kelly

RKNET said:
Wht is the general prctise for having try catch block and Finally.

try..catch has a different purpose from try..finally.

Try..catch handles errors, or possibly performs some cleanup which is
exclusive to the error scenario.

Try..finally performs cleanup in all situations.

Which one you use and when is dependent on what your requirements are.
I mean in one methods what are Cicrustances to have entire code in ONE try
catch block or MULTIPLE and which lines of code is not required /suppose to
be in TRY blocks.

This depends on what exceptions you need to catch and what cleanup needs
to happen. Basically, you should only catch exceptions that you can
meaningfully handle, and let other exceptions propagate to callers. For
cleanup (i.e. try..finally or the try..catch..rethrow pattern), it
depends on the kind of cleanup required.

-- Barry
 
H

Hans Kesting

Wht is the general prctise for having try catch block and Finally.
I mean in one methods what are Cicrustances to have entire code in ONE try
catch block or MULTIPLE and which lines of code is not required /suppose to
be in TRY blocks.
Thanking you in advance

You use a "try" block if you want special handling in case something
"goes wrong" (= thows an exception).

A "catch" block catches that exception. so you can do something special
in that case (for instance: log the error). You can have multiple catch
blocks, for different exceptions that require different handling.

A "finally" block is used to clean up: it is guaranteed to execute, no
matter how you exited the try/catch. One example is to make sure a
database connection is closed.


Hans Kesting
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top