Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817
Moderator: admin
lucian
Posts: 3 Joined: Tue Jul 05, 2016 10:44 am
Contact:
Post
by lucian » Fri Oct 07, 2016 7:19 am
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.
admin
Site Admin
Posts: 10065 Joined: Fri Sep 10, 2010 9:26 pm
Contact:
Post
by admin » Fri Oct 07, 2016 9:53 am
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
If you like our products and services, please help us by posting your
review here .
robhun79
Posts: 9 Joined: Thu Feb 02, 2023 12:18 pm
Contact:
Post
by robhun79 » Wed Mar 15, 2023 9:18 am
Both FileNotFoundException and InvalidClassException extend IOException - shouldnt this cause a compiler error in the catch clause?
admin
Site Admin
Posts: 10065 Joined: Fri Sep 10, 2010 9:26 pm
Contact:
Post
by admin » Wed Mar 15, 2023 11:14 am
Sorry, I did not understand your question. At which line are you expecting a compilation error and why?
If you like our products and services, please help us by posting your
review here .
robhun79
Posts: 9 Joined: Thu Feb 02, 2023 12:18 pm
Contact:
Post
by robhun79 » Fri Mar 24, 2023 1:48 pm
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?
admin
Site Admin
Posts: 10065 Joined: Fri Sep 10, 2010 9:26 pm
Contact:
Post
by admin » Fri Mar 24, 2023 9:14 pm
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.
If you like our products and services, please help us by posting your
review here .
Users browsing this forum: No registered users and 126 guests