Page 1 of 1

About Question enthuware.ocpjp.v8.2.1202 :

Posted: Fri Oct 07, 2016 7:19 am
by lucian
I don't understand who could throw the java.io.InvalidClassException ?

Code: Select all

    public static void copy(String records1, String records2) throws IOException {
        try (InputStream is = new FileInputStream(records1); 
              OutputStream os = new FileOutputStream(records2);) {
            byte[] buffer = new byte[1024];
            int bytesRead = 0;
            while ((bytesRead = is.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (FileNotFoundException | java.io.InvalidClassException e) {
            e.printStackTrace();
        }
    }
My first impression was that nobody can throw this exception and I answered it was a compilation error.

Re: About Question enthuware.ocpjp.v8.2.1202 :

Posted: Fri Oct 07, 2016 9:53 am
by admin
The code contains a call to InputStream's read method, which declares that it throws IOException. Therefore, the code for read method is free to throw any subclass of IOException, including InvalidClassException.

Hth,
Paul

Re: About Question enthuware.ocpjp.v8.2.1202 :

Posted: Wed Mar 15, 2023 9:18 am
by robhun79
Both FileNotFoundException and InvalidClassException extend IOException - shouldnt this cause a compiler error in the catch clause?

Re: About Question enthuware.ocpjp.v8.2.1202 :

Posted: Wed Mar 15, 2023 11:14 am
by admin
Sorry, I did not understand your question. At which line are you expecting a compilation error and why?

Re: About Question enthuware.ocpjp.v8.2.1202 :

Posted: Fri Mar 24, 2023 1:48 pm
by robhun79
I would have expected the compile error at this line:
catch (FileNotFoundException | java.io.InvalidClassException e)
Since both FileNotFoundException and InvalidClassException extend IOException, and shouldnt that cause a compile error in the multi-catch block?

Re: About Question enthuware.ocpjp.v8.2.1202 :

Posted: Fri Mar 24, 2023 9:14 pm
by admin
No, by that logic all exceptions extend from Throwable, so all multi catch will cause compilation error.

The issue is when you have a subclass and superclass exception in the same multicatch. e.g.

catch(IOException|FileNotFoundException e)

Try to some sample code to confirm.