Home > Blockchain >  In try with resources in java, what happens when there is an exception in close() when there is a ca
In try with resources in java, what happens when there is an exception in close() when there is a ca

Time:01-14

In this code, when there is an exception in br.close(), will catch block catch it or will the process be terminated?

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class TryWithBlock {
    public static void main(String args[])
    {
        System.out.println("Enter a number");
        try(BufferedReader br = new BufferedReader(new InputStreamReader(System.in)))
        {
            int i = Integer.parseInt(br.readLine());
            System.out.println(i);
        }
        catch(Exception e)
        {
            System.out.println("A wild exception has been caught");
            System.out.println(e);
        }
    }
}

CodePudding user response:

It will be catched because "Exception" will catch any kind of exception thrown.

CodePudding user response:

Exceptions thrown inside the try-with-resources statement are supressed. Exceptions thrown inside the try block are propagated. So in your case the catch block will catch the parsing exception (if any).

For more details you can refer at the docs.

  •  Tags:  
  • Related