Chapter 12 Quiz Study Guide

Ace your homework & exams now with Quizwiz!

What is a checked exception, and what is an unchecked exception?

* A checked exception must be explicitly declared in the method declaration, if a method throws it. A checked exception must be caught in a try-catch block. * An unchecked exception does not need to be declared and does not need to be caught. In Java, the only unchecked exceptions are RuntimeException and Error and their subclasses.

Suppose you enter 34.3, the ENTER key, 57.8, the ENTER key, abc, the Enter key. Analyze the following code. Line 1 Scanner input = new Scanner(System.in); Line 2 double v1 = input.nextDouble(); Line 3 double v2 = input.nextDouble(); Line 4 String line = input.nextLine();

* After line 2 is executed, v1 is 34.3. * After line 3 is executed, v2 is 57.8. * After line 4 is executed, line contains an empty string.

Suppose you enter 34.3, the ENTER key, 57.8, the ENTER key. Analyze the following code. Line 1 Scanner input = new Scanner(System.in); Line 2 double v1 = input.nextDouble(); Line 3 double v2 = input.nextDouble(); Line 4 String line = input.nextLine();

* After line 2 is executed, v1 is 34.3. * After line 3 is executed, v2 is 57.8. * After line 4 is executed, line contains an empty string.

Instances of _________ are unchecked exceptions.

* RuntimeException * Error * NumberFormatException

What are the reasons to create an instance of the File class?

* To determine whether the file exists. * To obtain the properties of the file such as whether the file can be read, written, or is hidden. * To rename the file. * To delete the file.

Which of the following statements are true? * You use the keyword throws to declare exceptions in the method heading. * A method may declare to throw multiple exceptions. * To throw an exception, use the key word throw. * If a checked exception occurs in a method, it must be either caught or declared to be thrown from the method.

* You use the keyword throws to declare exceptions in the method heading. * A method may declare to throw multiple exceptions. * To throw an exception, use the key word throw. * If a checked exception occurs in a method, it must be either caught or declared to be thrown from the method.

Which method can be used to create an output object for file temp.txt?

* new PrintWriter("temp.txt") * new PrintWriter(new File("temp.txt"))

Suppose that statement2 causes an exception in the following try-catch block: try { statement1; statement2; statement3; } catch (Exception1 ex1) { } catch (Exception2 ex2) { } statement4; Answer the following questions: 1. Will statement3 be executed? 2. If the exception is not caught, will statement4 be executed? 3. If the exception is caught in the catch block, will statement4 be executed?

1. No. 2. No. 3. Yes

Analyze the following code: public class Test { public static void main(String[] args) { try { int zero = 0; int y = 2/zero; try { String s = "5.6"; Integer.parseInt(s); // Cause a NumberFormatException } catch(Exception e) { } } catch(RuntimeException e) { System.out.println(e); } } }

A good programming practice is to avoid nesting try-catch blocks, because nesting makes programs difficult to read. You can rewrite the program using only one try-catch block. Explanation: The best answer is b. This question does not ask you what happens when you run the program. If you run the program, a RuntimeException would occur and it would be caught be the last catch clause.

Point out the problem in the following code. Does the code throw any exceptions? long value = Long.MAX_VALUE + 1; System.out.println(value);

Adding 1 to Long.MAX_VALUE exceeds the maximum value allowed by a long value. But the current versions of Java does not report this as an exception.

Suppose you enter 34.3 57.8 789, then press the ENTER key. Analyze the following code. Scanner input = new Scanner(System.in); double v1 = input.nextDouble(); double v2 = input.nextDouble(); String line = input.nextLine();

After the last statement is executed, line contains characters ' ', '7', '8', '9'.

Analyze the following program. public class Test { public static void main(String[] args) { try { String s = "5.6"; Integer.parseInt(s); // Cause a NumberFormatException int i = 0; int y = 2 / i; System.out.println("Welcome to Java"); } catch (Exception ex) { System.out.println(ex); } } }

An exception is raised due to Integer.parseInt(s); Explanation: Both (A) and (B) [int y = 2 / i] would cause exception, but (A) occurred first, so the exception is due to (A).

What exception type does the following program throw? public class Test { public static void main(String[] args) { System.out.println(1 / 0); } }

ArithmeticException

What is displayed when running the following program? public class Test { public static void main(String[] args) { try { method(); System.out.println("After the method call"); } catch (ArithmeticException ex) { System.out.println("ArithmeticException"); } catch (RuntimeException ex) { System.out.println("RuntimeException"); } catch (Exception e) { System.out.println("Exception"); } } static void method() throws Exception { System.out.println(1 / 0); } }

ArithmeticException Reason: method() throws ArithmeticException.

What exception type does the following program throw? public class Test { public static void main(String[] args) { int[] list = new int[5]; System.out.println(list[5]); } }

ArrayIndexOutOfBoundsException

What exception type does the following program throw? public class Test { public static void main(String[] args) { Object o = new Object(); String d = (String)o; } }

ClassCastException

What would be the output if the line int value = 30; were changed to int value = 50; ? public class Test { public static void main(String[] args) { try { int value = 30; if (value < 40) throw new Exception("value is too small"); } catch (Exception ex) { System.out.println(ex.getMessage()); } System.out.println("Continue after the catch block"); } }

Continue after the catch block

How do you create a Scanner object for reading text from a URL?

Create a URL object and use new Scanner(url.openStream()) to create a scanner object for reading data from the URL stream.

An instance of _________ describes system errors. If this type of error occurs, there is little you can do beyond notifying the user and trying to terminate the program gracefully.

Error

An instance of _________ describes the errors caused by your program and external circumstances. These errors can be caught and handled by your program.

Exception

Which of the following is not an advantage of Java exception handling? * Java separates exception handling from normal processing tasks. * Exception handling improves performance. * Exception handling makes it possible for the caller's caller to handle the exception. * Exception handling simplifies programming because the error-reporting and error-handling code can be placed at the catch block.

Exception handling improves performance.

Suppose the setRadius method throws the InvalidRadiusException defined in Listing 12.10. What is displayed when running the following program? public class Test { public static void main(String[] args) { try { method(); System.out.println("After the method call"); } catch (RuntimeException ex) { System.out.println("RuntimeException in main"); } catch (Exception ex) { System.out.println("Exception in main"); } } static void method() throws Exception { try { Circle c1 = new Circle(1); c1.setRadius(-1); System.out.println(c1.getRadius()); } catch (RuntimeException ex) { System.out.println("RuntimeException in method()"); } catch (Exception ex) { System.out.println("Exception in method()"); throw ex; } } }

Exception in method() Exception in main Reason: the setRadius method throws a RadiusException. RadiusException is a subclass of Exception. So it is caught in method()'s handler. The handler rethrows it back to the main method.

Which class contains the method for checking whether a file exists?

File

Which of the following statements are correct? I: File file = new File("input.txt"); try (Scanner input = new Scanner(file);) { String line = input.nextLine(); } II: try (File file = new File("input.txt"); Scanner input = new Scanner(file);) { String line = input.nextLine(); } III: File file; try (file = new File("input.txt"); Scanner input = new Scanner(file);) { String line = input.nextLine(); } IV: File file; Scanner input; try (file = new File("input.txt"); input = new Scanner(file);) { String line = input.nextLine(); }

I. Explanation: File is not a subtype of AutoCloseable. So it cannot be used to open a resource in a try-with-resources.

Which of the following statements are correct? I: try (PrintWriter output = new PrintWriter("output.txt");) { output.println("Welcome to Java"); } II: try (PrintWriter output = new PrintWriter("output.txt"); Scanner input = new Scanner(System.in);) { output.println(input.nextLine()); } III: PrintWriter output; try (output = new PrintWriter("output.txt");) { output.println("Welcome to Java"); } IV: try (PrintWriter output = new PrintWriter("output.txt");) { output.println("Welcome to Java"); } finally { output.close(); }

I. II. Explanation: III is wrong. You have to declare the resource reference variable and create the resource altogether in the try (?).

What will happen if you attempt to create a Scanner for a nonexistent file? What will happen if you attempt to create a PrintWriter for an existing file?

If you attempt to create a Scanner for a nonexistent file, an exception will occur. If you attempt to create a PrintWriter for an existing file, the contents of the existing file will be gone.

Does the presence of a try-catch block impose overhead when no exception occurs?

No

What exception type does the following program throw? public class Test { public static void main(String[] args) { Object o = null; System.out.println(o); } }

No exception

Can you use the File class for I/O? Does creating a File object create a file on the disk?

No. The File class can be used to obtain file properties and manipulate files, but cannot perform I/O. No. Creating a File object does not create a file/directory on the disk.

Is the line separator the same on all platforms? What is the line separator on Windows?

No. The line separator on Windows is \r\n.

Which of the following statements are true? * If a file (e.g., c:\temp.txt) does not exist, new File("c:\\temp.txt") returns null. * (e.g., c:\liang) does not exist, new File("c:\liang") returns null. * If a file (e.g., c:\temp.txt) does not exist, new File("c:\\temp.txt") creates a new file named c:\temp.txt. * If a directory (e.g., c:\liang) does not exist, new File("c:\liang") creates a new directory named c:\liang. * None of the above.

None of the above.

What exception type does the following program throw? public class Test { public static void main(String[] args) { Object o = null; System.out.println(o.toString()); } }

NullPointerException

Which class do you use to write data into a text file?

PrintWriter

An instance of _________ describes programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors.

RuntimeException

What is displayed when running the following program? public class Test { public static void main(String[] args) { try { int[] list = new int[10]; System.out.println("list[10] is " + list[10]); } catch (ArithmeticException ex) { System.out.println("ArithmeticException"); } catch (RuntimeException ex) { System.out.println("RuntimeException"); } catch (Exception ex) { System.out.println("Exception"); } } }

RuntimeException Reason: list[10] throws ArrayIndexOutOfBoundsException that is a subclass of RuntimeException.

What is displayed when running the following program? public class Test { public static void main(String[] args) { try { method(); System.out.println("After the method call"); } catch (RuntimeException ex) { System.out.println("RuntimeException in main"); } catch (Exception ex) { System.out.println("Exception in main"); } } static void method() throws Exception { try { String s ="abc"; System.out.println(s.charAt(3)); } catch (RuntimeException ex) { System.out.println("RuntimeException in method()"); } catch (Exception ex) { System.out.println("Exception in method()"); } } }

RuntimeException in method() After the method call Reason: s.charAt(3) throws StringIndexOutOfBoundsException that is a subclass of RuntimeException. This exception is caught in method(). The main method continues its normal execution flow.

Which class do you use to read data from a text file?

Scanner

What exception type does the following program throw? public class Test { public static void main(String[] args) { String s = "abc"; System.out.println(s.charAt(3)); } }

StringIndexOutOfBoundsException

Which of the following statements will throw an exception? System.out.println(1 / 0); System.out.println(1.0 / 0);

System.out.println(1 / 0); // Throws an exception

What is wrong about creating a File object using the following statement? new File("c:\book\test.dat");

The \ is a special character. It should be written as \\ in Java using the Escape sequence

What is the advantage of using exception handling?

The advantages of using exception handling: It enables a method to throw an exception to its caller. The caller can handle this exception. Without this capability, the called method itself must handle the exception or terminate the program. Often the called method does not know how to handle the exception. So it needs to pass the exception to its caller for handling.

Show the contents of the file temp.txt after the following program is executed. public class Test { public static void main(String[] args) throws java.io.IOException { java.io.PrintWriter output = new java.io.PrintWriter("temp.txt"); output.printf("amount is %f %e\r\n", 32.32, 32.32); output.printf("amount is %5.4f %5.4e\r\n", 32.32, 32.32); output.printf("%6b\r\n", (1 > 2)); output.printf("%6s\r\n", "Java"); output.close(); } }

The contents of the file temp.txt is: amount is 32.320000 3.232000e+01 amount is 32.3200 3.2320e+01 false Java

Correct a compile error in the following code: public void m(int value) { if (value < 40) throw new Exception("value is too small"); }

The method throws a checked exception. It must be caught or thrown. You may fix it as follows: public void m(int value) throws Exception { if (value < 40) throw new Exception("value is too small"); }

What is displayed on the console when running the following program? public class Test { public static void main(String[] args) { try { method(); System.out.println("After the method call"); } catch (RuntimeException ex) { System.out.println("RuntimeException"); } catch (Exception ex) { System.out.println("Exception"); } } static void method() throws Exception { try { String s = "5.6"; Integer.parseInt(s); // Cause a NumberFormatException int i = 0; int y = 2 / i; System.out.println("Welcome to Java"); } catch (NumberFormatException ex) { System.out.println("NumberFormatException"); throw ex; } catch (RuntimeException ex) { System.out.println("RuntimeException"); } } }

The program displays NumberFormatException followed by RuntimeException.

What is displayed on the console when running the following program? public class Test { public static void main(String[] args) { try { p(); System.out.println("After the method call"); } catch (NumberFormatException ex) { System.out.println("NumberFormatException"); } catch (RuntimeException ex) { System.out.println("RuntimeException"); } } static void p() { String s = "5.6"; Integer.parseInt(s); // Cause a NumberFormatException int i = 0; int y = 2 / i; System.out.println("Welcome to Java"); } }

The program displays NumberFormatException. The correct answer is A Explanation: It should be A. The main method invokes the method p. In p, Integer.parseInt(s) causes a NumberFormatException. The method p is now terminated. The NumberFormatException exception is handled in the main method. So NumberFormatException is displayed.

What is displayed on the console when running the following program? public class Test { public static void main(String[] args) { try { p(); System.out.println("After the method call"); } catch (RuntimeException ex) { System.out.println("RuntimeException"); } catch (Exception ex) { System.out.println("Exception"); } } static void p() throws Exception { try { String s = "5.6"; Integer.parseInt(s); // Cause a NumberFormatException int i = 0; int y = 2 / i; System.out.println("Welcome to Java"); } catch (RuntimeException ex) { System.out.println("RuntimeException"); } catch (Exception ex) { System.out.println("Exception"); } } }

The program displays RuntimeException followed by After the method call.

What is displayed on the console when running the following program? public class Test { public static void main(String[] args) { try { System.out.println("Welcome to Java"); int i = 0; int y = 2/i; System.out.println("Welcome to Java"); } finally { System.out.println("End of the block"); } System.out.println("End of the block"); } }

The program displays Welcome to Java and End of the block, and then terminates because of an unhandled exception.

What is displayed on the console when running the following program? public class Test { public static void main(String[] args) { try { System.out.println("Welcome to Java"); int i = 0; int y = 2/i; System.out.println("Welcome to Java"); } catch (RuntimeException ex) { System.out.println("Welcome to Java"); } finally { System.out.println("End of the block"); } System.out.println("End of the block"); } }

The program displays Welcome to Java two times followed by End of the block two times.

What is displayed on the console when running the following program? public class Test { public static void main(String[] args) { try { System.out.println("Welcome to Java"); int i = 0; int y = 2/i; System.out.println("Welcome to Java"); } catch (RuntimeException ex) { System.out.println("Welcome to Java"); } finally { System.out.println("End of the block"); } } }

The program displays Welcome to Java two times followed by End of the block.

What is displayed on the console when running the following program? public class Test { public static void main(String[] args) { try { System.out.println("Welcome to Java"); int i = 0; double y = 2.0 / i; System.out.println("Welcome to HTML"); } finally { System.out.println("The finally clause is executed"); } } }

The program displays three lines: Welcome to Java, Welcome to HTML, The finally clause is executed. Explanation: A floating number divided by 0 does not raise an exception.

Analyze the following code: public class Test { public static void main(String[] args) { try { String s = "5.6"; Integer.parseInt(s); // Cause a NumberFormatException int i = 0; int y = 2 / i; } catch (Exception ex) { System.out.println("NumberFormatException"); } catch (RuntimeException ex) { System.out.println("RuntimeException"); } } }

The program has a compile error. Explanation: catch (RuntimeException ex) should be specified before catch (Exception ex).

Suppose you enter 34.3 57.8 789, then press the ENTER key. Analyze the following code. Scanner input = new Scanner(System.in); int v1 = input.nextInt(); int v2 = input.nextInt(); String line = input.nextLine();

The program has a runtime error because 34.3 is not an integer.

What is the purpose of declaring exceptions? How do you declare an exception, and where? Can you declare multiple exceptions in a method header?

The purpose of declaring exceptions is to tell the Java runtime system what can go wrong. You declare an exception using the throws keyword in the method declaration. You can declare multiple exceptions, separated by commas.

A Java exception is an instance of __________.

Throwable

How do you define a custom exception class?

To define a custom class, extend Exception or a subclass of Exception.

What does the method printStackTrace() do?

To display trace information to the console.

What is displayed on the console when running the following program? public class Test { public static void main (String[] args) { try { System.out.println("Welcome to Java"); } finally { System.out.println("The finally clause is executed"); } } }

Welcome to Java followed by The finally clause is executed in the next line

What is displayed on the console when running the following program? public class Test { public static void main (String[] args) { try { System.out.println("Welcome to Java"); return; } finally { System.out.println("The finally clause is executed"); } } }

Welcome to Java followed by The finally clause is executed in the next line Explanation: The return statement exits the method, but before exiting the method, the finally clause is executed

What is displayed on the console when running the following program? public class Test { public static void main(String[] args) { try { System.out.println("Welcome to Java"); int i = 0; int y = 2 / i; System.out.println("Welcome to HTML"); } finally { System.out.println("The finally clause is executed"); } } }

Welcome to Java followed by The finally clause is executed in the next line, then an error message.

What does the JVM do when an exception occurs? How do you catch an exception?

When an excepion occurs, Java searches for a handler in the catch clause. So to catch an exception in your program, you need to write a try-catch statement like this: try { } catch (Exception ex) { // Catch and process exception }

What is wrong in the following program? public class Test { public static void main (String[] args) { try { System.out.println("Welcome to Java"); } } }

You cannot have a try block without a catch block or a finally block.

Analyze the following code: public class Test { public static void main(String[] args) throws MyException { System.out.println("Welcome to Java"); } } class MyException extends Error { }

You should not declare a class that extends Error, because Error raises a fatal error that terminates the program. Explanation: When an exception of Error type occurs, your program would terminate. Therefore, you should not declare an exception that extends Error. You declared an exception in the main method. If you did not throw anything, that is fine.

How do you throw an exception? Can you throw multiple exceptions in one throw statement?

You use the throw statement in the method to throw an exception. You cannot throw multiple exceptions in a single throw statement.

Show the output of the following code. (a) public class Test { public static void main(String[] args) { for (int i = 0; i < 2; i++) { System.out.print(i + " "); try { System.out.println(1 / 0); } catch (Exception ex) { } } } } (b) public class Test { public static void main(String[] args) { try { for (int i = 0; i < 2; i++) { System.out.print(i + " "); System.out.println(1 / 0); } } catch (Exception ex) { } } }

a. 0 1 b. 0

A method must declare to throw ________.

checked exceptions

Which of the following statements creates an instance of File on Window for the file c:\temp.txt?

new File("c:\\temp.txt")

Which of the following is used to test if a file c:\temp\test.txt exists?

new File("c:\\temp\\test.txt").exists()

Which method can be used to create an input object for file temp.txt?

new Scanner(new File("temp.txt"))

Which method can be used to read a whole line from the file?

nextLine

The following code causes Java to throw _________. int number = Integer.MAX_VALUE + 1;

no exceptions Explanation: At present, Java does not throw integer overflow exceptions. The future version of Java may fix this problem to throw an over flow exception.

To create an InputStream to read from a file on a Web server, you use the method __________ in the URL class.

openStream();

What is the output of the following code? public class Test { public static void main(String[] args) { try { int value = 30; if (value < 40) throw new Exception("value is too small"); } catch (Exception ex) { System.out.println(ex.getMessage()); } System.out.println("Continue after the catch block"); } }

output is value is too small Continue after the catch block

Which method can be used to write data?

print

What does the method getMessage() do?

the getMessage() is defined in the Throwable class to return a string that describes the exception.

What is the keyword throw used for? What is the keyword throws used for?

throw is for throwing exceptions and throws is for claiming exceptions.


Related study sets

Network+ Guide to Networks 7th ed. Quiz Ch. 10

View Set

Chapter 13 - Cardiac Arrhythmias And Their Electrocardiographic Interpretation

View Set

48-Hour Contracts and Regulations Course

View Set