Finally block not working in this code,shows Exception | Core Java Forum
S
Shinia Posted on 20/12/2021

package com.programming.java;

public class TryWithResourceWorksWithAutoCloseableInterface {

public static void main(String[] args) {
try {
TryWithResourceWorksWithAutoCloseableFeature();
}catch(Exception e)
{
System.out.println(e.getMessage());
}
try {
NormalTryCatchBlock();
}catch(Exception e)
{
System.out.println(e.getMessage());
}
}

static void TryWithResourceWorksWithAutoCloseableFeature() throws Exception{
try(MyResource obj=new MyResource()){
System.out.println("Instance of MyResource got created in try with resource Example");
if(true) {
throw new Exception("Exception in try with resource method");
}
}
}
static class MyResource implements AutoCloseable{
@Override
public void close() throws Exception {
System.out.println("Closing MyResource");
}

}

 


static void NormalTryCatchBlock() throws Exception {
MyResource mr=null;
System.out.println("MyResource obj got created as part ofsimple try catch method");
if(true) {
throw new Exception("Exception got invoked in simple try catch block");
}
finally {
if(mr!=null) {
mr.close();
}
}
}
}


Y
Yogesh Chawla Replied on 20/12/2021

Finally Block message did not print on console because if statement was not successfully or true(mr was actually null in your case) and if we initialize MyResource object then if statement will work and finally block statement will get printed on console. 
//Note: Finally Block will always work but post jdk 1.7 if AutoClosable functionality is used then finally block can be skipped.

Run this:

public class TryWithResourceWorksWithAutoCloseableInterface {

	public static void main(String[] args) {
		try {
			TryWithResourceWorksWithAutoCloseableFeature();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		try {
			NormalTryCatchBlock();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}

	static void TryWithResourceWorksWithAutoCloseableFeature()
			throws Exception {
		try (MyResource obj = new MyResource()) {
			System.out.println(
					"Instance of MyResource got created in try with resource Example");
			if (true) {
				throw new Exception("Exception in try with resource method");
			}
		}
	}
	static class MyResource implements AutoCloseable {
		@Override
		public void close() throws Exception {
			System.out.println("Closing MyResource");
		}

	}

	static void NormalTryCatchBlock() throws Exception {
		MyResource mr = null;
		System.out.println(
				"MyResource obj got created as part ofsimple try catch method");
		try {
			mr = new MyResource();
			if (true) {
				throw new Exception(
						"Exception got invoked in simple try catch block");
			}
		} finally {
			if (mr != null) {
				mr.close();
				System.out.println(
						"Finally always works in try-catch-finally block and"
								+ " can be skipped if we are using Autocloseable interface");
			}
		}
	}
}