Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

8.Consider the following class hierarchy and code fragments: java.lang.Throwable

ID: 3787856 • Letter: 8

Question

8.Consider the following class hierarchy and code fragments:

java.lang.Throwable

/

java.lang.Error java.lang.Exception

/

java.lang.OutOfMemoryError java.io.IOException

/

java.io.StreamCorruptedException java.net.MalformedURLException

1. try {

2. URL u = new URL(s); // assume s is previously defined

3. Object o = in.readObject(); // in is an ObjectInputStream

4. System.out.println( “Success” );

5. }

6. catch (MalformedURLException e) {

7. System.out.println(“Bad URL”);

8. }

9. catch (StreamCorruptedException e) {

10. System.out.println(“Bad file contents”);

11. }

12. catch (Exception e) {

13. System.out.println(“General exception”);14. }

15. finally {16. System.out.println(“doing finally part”);

17. }

18. System.out.println(“Carrying on”);

What lines are output if the method at line 3 throws an OutOfMemoryError?

A. Success

B. Bad URL

C. General Exception

E. doing finally part

f. Carrying on

9.Which one of the following fragments shows the most appropriate way to throw anexception? Assume that any undeclared variables have been appropriately declared elsewhere and are in scope and have meaningful values.

A. 1. Exception e = new IOException(“File not found”);

2. if (!f.exists()) { // f is a File object

3.throw e;

4. }

B.1. if (!f.exists()) { // f is a File object

2.throw new IOException( “File”+ f.getName() +“not _ found” );

3. }

C. 1. if (!f.exists()) {

2.throw IOException;

3. }

D.1. if (!f.exists()) {

2.throw“File not found” ;

3. }

E.1. if (!f.exists()) { // f is a File object

2. throw new IOException();

3. }

Explanation / Answer

There will be 3 outputs which will come up:

General Exception //When catching exceptions the more specific exceptions must be listed before the more general (the subclasses (java.lang.OutOfMemoryError) must be caught before the superclasses). So, in this case the General Exception will be call first.

Doing finally part // Final portion in try-catch block will always get printed

Carrying On // All the code after the finally statement is run because the exception has been caught.

9.

E.1. if (!f.exists()) { // f is a File object

2. throw new IOException();

3. }

It is the correct answer as The throw keyword is mainly used to throw custom exception.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote