Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finally block in try/catch not working?

Ok, as far as I understand, try/catch blocks try an operation and catch blocks catch exceptions. The more specific exceptions go up top, the more generic towards the bottom of the series of catch blocks. In the following code, I implement try/catch, everything works fine.

As far as I understand, a finally block always executes. Some people have argued that there is no purpose to finally block, because if there is an exception or there isn't, the code after the last catch block gets executed anyways.

However, the argument against this is that if there is an exception thrown in a catch block, there are no subsequent catch blocks to catch that exception. So by putting resource cleanup code in a finally block, you ensure that resources will be released in the event that an exception is thrown in a catch block.

Which is why the following code puzzles me. I throw an exception in the first catch block and the finally block never executes. Why?

*Please note that there is indeed an exception thrown while creating myStreamReader, as the file is actually called generic.txt and is misspelled with purpose, in order to throw the initial exception.

StreamReader myStreamReader = null;

try
{
   myStreamReader = new StreamReader("c:\\genneric.txt");   
   Console.WriteLine(myStreadReader.ReadToEnd());       
}

catch(FileNotFoundException Error)
{
   Console.WriteLine(Error.Message);
   Console.WriteLine(); 
   throw new Exception();
}

catch(Exception Error)
{
   Console.WriteLine(Error.Message);
   Console.WriteLine();
}

finally
{

  if(myStreamReader != null)
  {
    myStreamReader.Close();
  }

  Console.WriteLine("Closed the StreamReader.");
}

VIDEO:

The issue with this block of code originates in this video, at the 27:20 mark:

https://www.youtube.com/watch?v=WxdSb3ZCWYc&list=PLAC325451207E3105&index=41

The guy directly declares that an Exception that occurs in a catch block will not prevent the finally block from executing. I am seeing that it does.

like image 638
user3308043 Avatar asked Mar 13 '14 07:03

user3308043


People also ask

Can I use Finally in try-catch?

The try... catch statement is comprised of a try block and either a catch block, a finally block, or both. The code in the try block is executed first, and if it throws an exception, the code in the catch block will be executed.

Can we write try-catch in finally block?

No, we cannot write any statements in between try, catch and finally blocks and these blocks form one unit.

When finally block will not run?

A finally block will not execute due to other conditions like when JVM runs out of memory when our java process is killed forcefully from task manager or console when our machine shuts down due to power failure and deadlock condition in our try block.

Is finally in try-catch always executed?

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs.


1 Answers

If that new exception is completely unhandled, the entire process is torn down, and the finally block never gets to run.

If there's some other exception handler at a higher level, or an unhandled exception handler has been installed, the finally block does run.


This sample does show "Closed the StreamReader":

    static void Main()
    {
        try
        {
            StreamReader myStreamReader = null;

            try
            {
                myStreamReader = new StreamReader("c:\\genneric.txt");
                Console.WriteLine(myStreamReader.ReadToEnd());
            }

            catch (FileNotFoundException Error)
            {
                Console.WriteLine(Error.Message);
                Console.WriteLine();
                throw new Exception();
            }

            catch (Exception Error)
            {
                Console.WriteLine(Error.Message);
                Console.WriteLine();
            }

            finally
            {

                if (myStreamReader != null)
                {
                    myStreamReader.Close();
                }

                Console.WriteLine("Closed the StreamReader.");
            }
        }
        catch
        {

        }
        Console.WriteLine("Done");
        Console.ReadLine();
    }

Unhandled exception handlers can be registered in the AppDomain.UnhandledException event.

like image 126
Damien_The_Unbeliever Avatar answered Oct 07 '22 11:10

Damien_The_Unbeliever