Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a 'try-finally' block without a 'catch' block

Are there situations where it is appropriate to use a try-finally block without a catch block?

like image 653
mkus Avatar asked Feb 15 '12 10:02

mkus


People also ask

Can finally block be used without catch?

Yes, it is not mandatory to use catch block with finally.

What happens if there is no catch block?

If there is no catch block the programme will terminate giving the exception but still final block will execute. If there is only try block no catch and no final then it will give a compile error.


2 Answers

You would use it to ensure some actions occur after the try content or on an exception, but when you don't wish to consume that exception.

Just to be clear, this doesn't hide exceptions. The finally block is run before the exception is propagated up the call stack.

You would also inadvertently use it when you use the using keyword, because this compiles into a try-finally (not an exact conversion, but for argument's sake it is close enough).

try {     TrySomeCodeThatMightException(); } finally {     CleanupEvenOnFailure(); } 

Code running in finally is not guaranteed to run, however the case where it isn't guaranteed is fairly edge - I can't even remember it. All I remember is, if you are in that case, chances are very good that not running the finally isn't your biggest problem :-) so basically don't sweat it.

Update from Tobias: finally will not run if the process is killed.

Update from Paddy: Conditions when finally does not execute in a .net try..finally block

The most prevalent example you may see is disposing of a database connection or external resource even if the code fails:

using (var conn = new SqlConnection("")) // Ignore the fact we likely use ORM ;-) {     // Do stuff. } 

Compiles into something like:

SqlConnection conn;  try {     conn = new SqlConnection("");     // Do stuff. } finally {     if (conn != null)         conn.Dispose(); } 
like image 99
Adam Houldsworth Avatar answered Oct 15 '22 11:10

Adam Houldsworth


Good Explaination using code:

void MyMethod1() {     try     {         MyMethod2();         MyMethod3();     }     catch(Exception e)     {         //do something with the exception     } }   void MyMethod2() {     try     {         //perform actions that need cleaning up     }     finally     {         //clean up     } }   void MyMethod3() {     //do something } 

If either MyMethod2 or MyMethod3 throws an exception, it will be caught by MyMethod1. However, the code in MyMethod2 needs to run clean up code, e.g. closing a database connection, before the exception is passed to MyMethod1.

http://forums.asp.net/t/1092267.aspx?Try+without+Catch+but+with+finally+doesn+t+throw+error+Why+no+syntax+error+

like image 31
donstack Avatar answered Oct 15 '22 10:10

donstack