Does A Finally Block Always Get Executed In Java?

In this post, we will find out Does A Finally Block Always Get Executed In Java? Yes, finally block is only designed to be executed every time whenever the program is running irrespective of occurring of the exception and handling it as it is independent of occurring of the exception.

 Finally Block Always Get Executed In Java

Exception Handling In Java

Exception handling is an oops concept where we deal with the error that might occur during the execution of a program to handle those errors we have a concept called exceptional handling and it has three blocks

Try Block

It is the block that contains the probable error statement, which means where there is a probability of occurring an error. We can try a number of statements to check the exception which might occur during the execution.

It is designed so that we can easily find where things might go wrong.

Catch Bock

It is a block that is always followed by a try block which needs to execute if the exception occurs or there something went wrong we can say the exit place for the error occurred in a try block so the catch block must be followed by the try block.

We can have multiple catch blocks for each exception as we can try a number of conditions in a try block. for each error, there is a specific error statement that we can follow in the catch block.

Finally Block

It is also a block we come without any conditions and it has all the right to execute at any condition whether the exception will occur or not it does have to do anything with an exception occurring.

class ArgumentOutOfRangeExample
{
    public static void Main()
    {
        int[] array1 = {0, 0};
        int[] array2 = {0, 0};

        try
        {
            Array.Copy(array1, array2, -1);
        }
        catch (ArgumentOutOfRangeException e)
        {
            System.out.prinln("Error: {0}", e);
            throw;
        }
        finally
        {
            System.out.prinln("This statement is always executed.");
        }
    }
}

the example given above is self-explanatory and can get an idea of the execution of exceptional handling and finally block.

 

Learn more about Does A Finally Block Always Get Executed In Java?: Finally Block

And also Visit Java Tutorials for solving more problems related to java for python also visit Python’s list: What is the difference Between methods Append and Extend? to keep on learning new things and solve your problems.

 

Leave a Comment

%d bloggers like this: