12: Exception Handling and Text I/O

¡Supera tus tareas y exámenes ahora con 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.

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

A. An exception is raised due to Integer.parseInt(s);

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"); } } A. The program displays NumberFormatException. B. The program displays NumberFormatException followed by After the method call. C. The program displays NumberFormatException followed by RuntimeException. D. The program has a compile error. E. The program displays RuntimeException.

A. The program displays NumberFormatException.

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 { } A. You should not declare a class that extends Error, because Error raises a fatal error that terminates the program. B. You cannot declare an exception in the main method. C. You declared an exception in the main method, but you did not throw it. D. The program has a compile error.

A. You should not declare a class that extends Error, because Error raises a fatal error that terminates the program.

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

A. You use the keyword throws to declare exceptions in the method heading. B. A method may declare to throw multiple exceptions.

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.

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

ArithmeticException

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.

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

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. A try-catch block cannot be embedded inside another try-catch block. B. 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. C. The program has a compile error because Exception appears before RuntimeException. D. None of the above.

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

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

B. Exception handling improves performance.

hat 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"); } } } A. The program displays Welcome to Java three times followed by End of the block. B. The program displays Welcome to Java two times followed by End of the block. C. The program displays Welcome to Java three times. D. The program displays Welcome to Java two times.

B. 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"); return; } finally { System.out.println("The finally clause is executed"); } } }

B. 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"); } } } A. Welcome to Java B. Welcome to Java followed by The finally clause is executed in the next line C. The finally clause is executed D. None of the above

B. 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"); int i = 0; int y = 2 / i; System.out.println("Welcome to HTML"); } finally { System.out.println("The finally clause is executed"); } } } A. Welcome to Java, then an error message. B. Welcome to Java followed by The finally clause is executed in the next line, then an error message. C. The program displays three lines: Welcome to Java, Welcome to HTML, The finally clause is executed, then an error message. D. None of the above.

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

What is wrong in the following program? public class Test { public static void main (String[] args) { try { System.out.println("Welcome to Java"); } } } A. You cannot have a try block without a catch block. B. You cannot have a try block without a catch block or a finally block. C. A method call that does not declare exceptions cannot be placed inside a try block. D. Nothing is wrong.

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

Which of the following statements creates an instance of File on Window for the file c:\temp.txt? A. new File("c:\temp.txt") B. new File("c:\\temp.txt") C. new File("c:/temp.txt") D. new File("c://temp.txt")

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

Which of the following is used to test if a file c:\temp\test.txt exists? A. new File("c:\temp\test.txt").exists() B. new File("c:\\temp\\test.txt").exists() C. new File("c:\temp\test.txt").exist() D. new File("c:\\temp\\test.txt").exist() E. None of the above.

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

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"); } } } A. The program displays NumberFormatException twice. B. The program displays NumberFormatException followed by After the method call. C. The program displays NumberFormatException followed by RuntimeException. D. The program has a compile error.

C. The program displays NumberFormatException followed by RuntimeException.

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"); } } } A. The program displays RuntimeException twice. B. The program displays Exception twice. C. The program displays RuntimeException followed by After the method call. D. The program displays Exception followed by RuntimeException. E. The program has a compile error.

C. 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"); } catch (RuntimeException ex) { System.out.println("Welcome to Java"); } finally { System.out.println("End of the block"); } System.out.println("End of the block"); } } A. The program displays Welcome to Java three times followed by End of the block. B. The program displays Welcome to Java two times followed by End of the block. C. The program displays Welcome to Java two times followed by End of the block two times. D. You cannot catch RuntimeException errors.

C. 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; double y = 2.0 / i; System.out.println("Welcome to HTML"); } finally { System.out.println("The finally clause is executed"); } } } A. Welcome to Java. B. Welcome to Java followed by The finally clause is executed in the next line. C. The program displays three lines: Welcome to Java, Welcome to HTML, The finally clause is executed. D. None of the above.

C. The program displays three lines: Welcome to Java, Welcome to HTML, The finally clause is executed.

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 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"); } } A. The program displays Welcome to Java three times followed by End of the block. B. The program displays Welcome to Java two times followed by End of the block. C. The program displays Welcome to Java two times followed by End of the block two times. D. The program displays Welcome to Java and

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

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. The program displays NumberFormatException. B. The program displays RuntimeException. C. The program displays NumberFormatException followed by RuntimeException. D. The program has a compile error.

D. The program has a compile 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.

Error

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.

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

Exception

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.

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

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.

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

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.

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

RuntimeException

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.

Instances of _________ are unchecked exceptions.

RuntimeException, Error, NumberFormatException

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

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.

A Java exception is an instance of____________

Throwable

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.

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.

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

A method must declare to throw ________.

checked exceptions

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

int number = Integer.MAX_VALUE + 1;

no exceptions

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.


Conjuntos de estudio relacionados

Chapter 12 Terms - AP Psycholgoy

View Set

Increased Intracranial Pressure (ICP)

View Set

English IIB, Week 10 vocab, Unit 5

View Set

FIN Ch. 10 Capital Budgeting Technique

View Set

Perioperative Nursing Care Questions

View Set

Nut 10 - : Chapter 11 + 12 from Nutrition Basics for Better Health and Performance

View Set

Distance and displacement problems- ENR

View Set