Page 1 of 1

About Question enthuware.ocpjp.v11.2.1255 :

Posted: Sun Jan 24, 2021 1:15 pm
by mingzhou
If you try the code below, it would print "Exception" instead of "ClassNotFound", why the anwser is ClassNotFoundException?

Code: Select all

public void readData(String fileName) throws Exception {
        try (FileReader fr1 = new FileReader(fileName)) {
            Connection c = getConnection();
        }
    }

    public static void main(String[] args) {
        try {
            new Test().readData("ss");
        }
        catch (ClassNotFoundException e) {
            System.out.println("ClassNotFound");
        } catch (Exception e) {
            System.out.println("Exception");
        }
    }

Re: About Question enthuware.ocpjp.v11.2.1255 :

Posted: Sun Jan 24, 2021 9:26 pm
by admin
Because as per the problem statement, it is given that getConnection() throws ClassNotFoundException. The code that you have posted here doesn't do that. Please post complete code that you are trying to run.

Re: About Question enthuware.ocpjp.v11.2.1255 :

Posted: Sat Dec 14, 2024 9:19 am
by aurelios
This is a really tricky question. I had to run a couple of times and am still struggling with it.
So :
1. if an exception is thrown before the try-catch-with-resource block(inside try() for example) for example FileNotFoundException then the caller will get Exception
2. if an exception is thrown inside a try-catch-with-resources block, for example, ClassNotFoundException then this is what the caller will get BUT, if something happens after the try-block return, on close for example an IOException, then IOException will be added as a suppressed warning into ClassNotFoundException and the caller will get ClassNotFoundException

is that correct?

Re: About Question enthuware.ocpjp.v11.2.1255 :

Posted: Sun Dec 15, 2024 5:36 pm
by admin
1. No, if a FileNotFoundException is thrown from try(code here), then caller will get FileNotFoundException.
2. Yes, that is correct.