Chapter 12 Quiz Study Guide

¡Supera tus tareas y exámenes ahora con Quizwiz!

Throwable

A Java exception is an instance of __________.

checked exceptions

A method must declare to throw ________.

RuntimeException

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

Error

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.

Exception

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

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.

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 { }

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

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"); } } }

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.

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); } } }

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).

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); } } }

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.

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

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"); }

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

No

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

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

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

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

How do you define a custom exception class?

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

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

* RuntimeException * Error * NumberFormatException

Instances of _________ are unchecked exceptions.

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

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

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.

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

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

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(); } }

a. 0 1 b. 0

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) { } } }

1. No. 2. No. 3. Yes

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?

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.

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; } } }

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

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();

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

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 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, 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();

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.

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

openStream();

To create an InputStream to read from a file on a Web server, you use the method __________ in the URL 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.

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

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 does the JVM do when an exception occurs? How do you catch an exception?

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

What does the method getMessage() do?

To display trace information to the console.

What does the method printStackTrace() do?

ClassCastException

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; } }

No exception

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

NullPointerException

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()); } }

StringIndexOutOfBoundsException

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)); } }

ArithmeticException

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

ArrayIndexOutOfBoundsException

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]); } }

* 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.

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

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"); return; } 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"); } 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.

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"); } } }

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

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"); } } }

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"); } 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; 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 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"); } finally { System.out.println("End of the block"); } System.out.println("End of the block"); } }

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 { 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. 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 (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 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 { 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"); } } }

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 { 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 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.

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()"); } } }

ArithmeticException Reason: method() throws 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); } }

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.

What is the advantage of using exception handling?

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

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

output is value is too small Continue after the catch block

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"); } }

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.

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 \ is a special character. It should be written as \\ in Java using the Escape sequence

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

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

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

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.

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?

Continue after the catch block

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"); } }

File

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

Scanner

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

PrintWriter

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

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

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

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

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

nextLine

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

print

Which method can be used to write data?

Exception handling improves performance.

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.

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

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

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: 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. II. Explanation: III is wrong. You have to declare the resource reference variable and create the resource altogether in the try (?).

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(); }

None of the above.

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.

* 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 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.

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

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

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

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


Conjuntos de estudio relacionados

Chapter 9 PRE, HW, and Clicker Questions

View Set

NRS222 Mental health and mental illness

View Set

Ch. 11 Fundamentals of the Nervous System and Nervous Tissue

View Set

Chapter 3 Health, Policy, Politics and Reform

View Set

Smart Book Assignment -Ch 12 - Solutions

View Set

Ky Property and Casualty Exam Notes

View Set