Chapter 12 JAVA PROGRAMMING Exception Handling and Text I/O

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

12.14 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" because an ArrayIndexOutOfBoundsException is a subclass of runtime exception

12.13 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, the program will terminate. 3. Yes. Depends on the how the catch handles the exception.

12.23 Suppose that statement2 may cause an exception in the following code: try { statement1; statement2; statement3; } catch (Exception1 ex1) { } catch (Exception2 ex2) { throw ex2; } finally { statement4; } statement5; Answer the following questions: 1. If no exception occurs, will statement4 be executed, and will statement5 be executed? 2. If the exception is of type Exception1, will statement4 be executed, and will statement5 be executed? 3. If the exception is of type Exception2, will statement4 be executed, and will statement5 be executed? 4. If the exception is not Exception1 nor Exception2, will statement4 be executed, and will statement5 be executed?

1. Yes to both. 2. Yes to both. 3. This exception is caught by the catch (Exception2 e2) clause and statement4 will be executed, but statement5 will not be executed because it is rethrown to its caller. 4. This exception is not caught. statement4 will be executed, but statement5 will not be executed.

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

12.3 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. This would printout the Min_value.

Error, Exception, Runtime Error

All three classes are exceptions and all occur at runtime.

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

Runtime errors

Errors that occur while a program is running if the JVM detects an operation that is impossible to carry out. Ex: ArrayIndexOutOfBounds attempting to access an array using an index that is out of bounds. Ex. InputMismatchException when a the program receives a double value when expecting an integer.

System Errors

Errors thrown by the JVM and represented in the Error class. @describes internal system errors (rarely occur) @there is really no handling other than to notify the user and trying to terminate the program gracefully.

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

checked exceptions

Exceptions that the compiler forces the programmer to check and eal with in a try-catch block or declare the it in the method header.

Absolute file name

File name that contains the full path and file name Ex: C:\book\WelcomeJava @do not use absolute file names as they are machine dependent

throws keyword

For all checked exceptions, the method should have the throw keyword to indicate what kind of error it can throw. EX: public void myMethod() throws IOException @Multiple potential exceptions can be specified separated by a comma.

12.34 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 Formatter for an existing file, the contents of the existing file will be gone.

What is a benefit of Exception Handling?

It enables a program to deal with exceptional situations and continue its normal execution. It enables a method to throw an exception to its caller, enabling the caller to handle the exception. With out this, the called method must handle the exception and it rarely knows how.

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

No.

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.

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

Runtime Exceptions

Represented by the Runtime Exception class. Describe programming errors, such as bad casting, accessing an out of bounds array and numeric errors. Usually thrown by the JVM.

unchecked exceptions

Runtime and System Error exceptions.

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

12.2 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 System.out.println(1.0 / 0); // Will not throw an exception

12.7 Describe the Java Throwable class, its subclasses, and the types of exceptions.

The Throwable class is the root of Java exception classes. Error and Exception are subclasses of Throwable. Error describes fatal system errors, and Exception describes the errors that can be handled by Java programs. The subclasses of Error are LinkageError, VirtualMachineError, and AWTError. The subclasses of Exception include RuntimeException, IOException, AWTException, and InstantiationException.

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

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

12.31 Show the contents of the file temp.txt after the following program is executed. public class Test { public static void main(String[] args) throws Exception { 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

12.24 What would be the output if line 16 is replaced by the following line? throw new Exception("New info from method1");

The output will be java.lang.Exception: New info from method1 at ChainedExceptionDemo.method1(ChainedExceptionDemo.java:16) at ChainedExceptionDemo.main(ChainedExceptionDemo.java:4)

directory path

The path to the directory a file is housed. Ex: C:\book\

Catching an exception

The process of finding a handler. @if a catch block catches exception objects of a superclass, it can catch all the exception objects of the subclasses of that superclass @Order of the catch block is important. Any specific subclass exceptions must be before the superclass or it will cause a compiler error.

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

File Class

This class contains the methods for obtaining the properties of a file/directory and for renaming and deleting a file/directory. @this class is intended to provide an abstraction that deals with most machine dependent complexities of file and path names @this class does not contain methods for reading and writing file contents.

finally clause

This clause is always executed whether there is an exception or not.

Throwable Class

This is the root class of the exceptions classes of which all inherit directly or indirectly.

12.30 How do you create a PrintWriter to write data to a file? What is the reason to declare throws Exception in the main method in Listing 12.13, WriteData.java? What would happen if the close() method were not invoked in Listing 12.13?

To create a PrintWriter for a file, use new PrintWriter(filename). This statement may throw an exception. Java forces you to write the code to deal with exceptions. One way to deal with it is to declare throws Exception in the method declaration. If the close() method is not invoked, the data may not be saved properly.

12.33 How do you create a Scanner to read data from a file? What is the reason to define throws Exception in the main method in Listing 12.15, ReadData.java? What would happen if the close() method were not invoked in Listing 12.15?

To create a Scanner for a file, use new Scanner(new File(filename)). This statement may throw an exception. Java forces you to write the code to deal with exceptions. One way to deal with it is to declare throws Exception in the method declaration. If the close() method is not invoked, the problem will run fine. But it is a good practice to close the file to release the resource on the file.

12.25 How do you define a custom exception class?

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

12.18 What does the method printStackTrace() do?

To display trace information to the console.

12.28 How do you check whether a file already exists? How do you delete a file? How do you rename a file? Can you find the file size (the number of bytes) using the File class? How do you create a directory?

Use exists() in the File class to check whether a file exists. Use delete() in the File class to delete this file. Use renameTo(File) to rename the name for this file. Use length() to return the file size. Use mkdir or mkdirs to create a directory under this File object.

chained exceptions

When a new exception is thrown with additional information all with the original exception.

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

When an exception 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 }

12.22 The following method tests whether a string is a numeric string: public static boolean isNumeric(String token) { try { Double.parseDouble(token); return true; } catch (java.lang.NumberFormatException ex) { return false; } } Is it correct? Rewrite it without using exceptions.

Yes. It is correct. But a better way to write this method is using regular expression to test if the string is numeric.

12.39 Before a URL is added to listOfPendingURLs, line 25 tests whether it has been traversed. Is it possible that listOfPendingURLs contains duplicate URLs? If so, give an example.

Yes. Possible. Suppose link1 is not in listOfTraversedURLs, but it appears more than one time in a page. Duplicate link1 will be added into listOfPendingURLs.

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

throwing an exception

a program detecting an error creating an instance of an appropriate exception type and throwing it.

12.6 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

12.21 Suppose you run the following code: public static void main(String[] args) throws Exception2 { m(); statement7; } public static void m() { try { statement1; statement2; statement3; } catch (Exception1 ex1) { statement4; } finally { statement5; } statement6; } answer the questions: 1. If no exception occurs, which statements are executed? 2. If statement2 throws an exception of type Exception1, which statements are executed? 3. If statement2 throws an exception of type Exception2, which statements are executed? 4. If statement2 throws an exception that is neither Exception1 nor Exception2, which statements are executed?

a. 123567 b. 124567 c. 125 d. 125

What RuntimeException will the following programs throw, if any? (a) public class Test { public static void main(String[] args) { System.out.println(1 / 0); } } (b) public class Test { public static void main(String[] args) { int[] list = new int[5]; System.out.println(list[5]); } } (c) public class Test { public static void main(String[] args) { String s = "abc"; System.out.println(s.charAt(3)); } } (d) public class Test { public static void main(String[] args) { Object o = new Object(); String d = (String)o; } } (e) public class Test { public static void main(String[] args) { Object o = null; System.out.println(o.toString()); } } (f) public class Test { public static void main(String[] args) { System.out.println(1.0 / 0); } }

a. Arithmetic Exception error (RunTime) b. ArrayIndexOutOfBoundsException c. IStringIndexOutOfBoundsException (Runtime) d. ClassCastException e. NullPointerException f. none.

Exception

an object that represents an error or condition that prevents execution from proceeding normally. @exceptions are thrown from a method. @the caller of the method can catch and handle the exception @is an object @root class is java.lang.Throwable

catch block

catches the exception that is thrown by the method contains the code that handles the exception

try block

contains the code that is executed in normal circumstances

Java Exception Handling Model

declaring an exception, throwing an exception, catching an exception

propagating the exception

follows the path backward from the current method. each catch block is examined from first to last to see whether the exception is of a type that is handled. @if no handler is found, the program is ungracefully terminated.

12.36 Suppose you enter 45 57.8 789, then press the Enter key. Show the contents of the variables after the following code is executed. Scanner input = new Scanner(System.in); int intValue = input.nextInt(); double doubleValue = input.nextDouble(); String line = input.nextLine();

intValue = 45; doubleValue = 57.8; line = null;

relative file name

is in relation to the current working directory Ex: WelcomeJava

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

new Scanner(URL);

12.5 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"); } } What would be the output if the line int value = 30; were changed to int value = 50;

output is value is too small Continue after the catch block The output would be if Line int value = 30; is changed to int value = 50; Continue after the catch block

12.32 Rewrite the code in the preceding question using a try-with-resources syntax.

public class Test { public static void main(String[] args) throws Exception { try (java.io.PrintWriter output = new java.io.PrintWriter("temp.txt");) { output.printf("amount is %f %e ", 32.32, 32.32); output.printf("amount is %5.4f %5.4e ", 32.32, 32.32); output.printf("%6b ", (1 > 2)); output.printf("%6s ", "Java"); } } }

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

public void m(int value) throws Exception{ if (value < 40) throw new Exception("value is too small"); }

Scanner Class

reades data from an input or file

Exceptions x2

represented in the Exceptions class, which describes errors caused by the program or external circumstances. @should be caught and handled by the program

exception handler

the code that handles the exception in the catch block.

throw an exception

the execution of a throw statement

12.17 What does the method getMessage() do?

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

caller

the portion of the program that calls a method that could generate an exception. @the caller should handle the exception, not the method.

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

PrintWriter Class

writes data to console or file.


Ensembles d'études connexes

Cognitive Psychology- Ch. 3 Practice Questions

View Set

Indiana Life and Health-Life Insurance Policies

View Set

WFG- Completing the Application, Underwriting, and Delivering the Policy

View Set

Path 370 Assessment 2 (CH. 10, 11, 13, 14, 15)

View Set

Pre-Lecture Quizzes: Peri-operative

View Set