Module 4
Analyze the following program. public class Test {public static void main(String[] args) {try {String s = "5.6";Integer.parseInt(s); // Cause a NumberFormatExceptionint 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); Explanation: Both (A) and (B) 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);}}
A. ArithmeticException
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");) {output.println("Welcome to Java");}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();}
A. I B. II C. III
An instance of _________ describes programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors..
A. RuntimeException
An instance of _________ are unchecked exceptions.
A. RuntimeException C. Error E. NumberFormatException
When creating a client on a server port that is already in use, __________.
A. To determine whether the file exists. B. To obtain the properties of the file such as whether the file can be read, written, or is hidden. C. To rename the file. D. To delete the file.
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.
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.
An instance of _________ describes the errors caused by your program and external circumstances. These errors can be caught and handled by your program.
B. Exception
Which of the following returns the path separator character?
B. File.pathSeparatorChar
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");}}}
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");}}}
B. Welcome to Java followed by The finally clause is executed in the next line
What is wrong in the following program? public class Test {public static void main (String[] args) {try {System.out.println("Welcome to Java");}}}
B. You cannot have a try block without a catch block or a finally block.
A method must declare to throw ________.
B. checked exceptions
Which of the following statements creates an instance of File on Window for the file c:\temp.txt?
B. new File("c:\\temp.txt")
Which method can be used to read a whole line from the file?
B. nextLine
Which method can be used to write data?
B. print
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.
C. Error
Which class do you use to read data from a text file?
C. Scanner
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 NumberFormatExceptionint 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");}}}
C. 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 NumberFormatExceptionint 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");}}}
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");}}
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");}}}
C. 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.
Which method can be used to create an input object for file temp.txt?
C. new Scanner(new File("temp.txt"))
To create an InputStream to read from a file on a Web server, you use the method __________ in the URL class.
C. openStream();
is to rethrow an exception along with another exception.
Chained Exception
must be declared or placed in a try-catch block.
Checked Exception
Write a statement that deletes the file or directory represented in the File object f.
Checkf.delete();
Analyze the following code: public class Test {public static void main(String[] args) {try {String s = "5.6";Integer.parseInt(s); // Cause a NumberFormatExceptionint i = 0;int y = 2 / i;}catch (Exception ex) {System.out.println("NumberFormatException");}catch (RuntimeException ex) {System.out.println("RuntimeException");}}}
D. The program has a compile error. Explanation: catch (RuntimeException ex) should be specified before catch (Exception ex).
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.
D. Throwable
Which of the following statements are true? A. If a file (e.g., c:\temp.txt) does not exist, new File("c:\\temp.txt") returns null. B. If a directory (e.g., c:\liang) does not exist, new File("c:\liang") returns null. C. If a file (e.g., c:\temp.txt) does not exist, new File("c:\\temp.txt") creates a new file named c:\temp.txt. D. If a directory (e.g., c:\liang) does not exist, new File("c:\liang") creates a new directory named c:\liang. E. None of the above.
E. None of the above.
The following code causes Java to throw _________. int number = Integer.MAX_VALUE + 1;
E. 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.
is to catch an exception through a chain of method calls.
Exception Propagation
Write a statement that declares a reference variable e suitable for holding a reference to an Exception object.
Exception e;
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 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: File file = new File("input.txt");try (Scanner input = new Scanner(file)) { String line = input.nextLine();} Explanation: File is not a subtyp of AutoCloseable. So it cannot be used to open a resource in a try-with-resources.
Suppose that statement2 causes an exception in the following statement:try {statement1;statement2;statement3;}catch (Exception ex1) {}finally {statement4;}statement5;Answer the following questions:a. If no exception occurs, will statement4 be executed , and will statement5 be executed?b. If the exception is of type Exception1, will statement4 be executed, and will statement5 be executed?c. If the execution is not of type Exception1, will statement4 be executed, and will statement5 be executed?
If no exception occurs, the statement 4 and statement 5 will be executed. The statements in the finally block and the statements after the try block will be executed when no exception arises in the try block.If the exception is of type Exception1, the exception is caught in the catch block and the staement 4 and statement 5 will be executed. When an exception is caught in the catch block, the statements in the finally block and the statements next to the try block will be executed.If the exception is not of type Exception1, the exception is not caught in the catch block. So the statement 4 is executed and the statement 5 will not be executed. When an exception is not caught in the catch block, the other statements in the try block are skipped and the finally clause is executed.
Write a sequence of statements that create a file named "greeting" and write a single line consisting of "Hello, World!" to that file. Make sure that the line has been flushed to the file and that any system resources used during the course of running these statements have been released.(Do not concern yourself with any possible exceptions here—assume they are handled elsewhere.)
PrintWriter output = new PrintWriter("greeting"); output.println("Hello, World!"); output.close();
Given an initialized String variable outfile, write a statement that declares a PrintWriter reference variable named output and initializes it to a reference to a newly created PrintWriter object associated with a file whose name is given by outfile.(Do not concern yourself with any possible exceptions here—assume they are handled elsewhere.)
PrintWriter output = new PrintWriter(outfile);
Declare a local variable output that is suitable for referring to an object that provides methods for writing to a text file.
PrintWriter output;
Declare a variable logfileName that is suitable for holding the name of a file.
String logfileName;
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
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.
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 (NumberFormatException ex) {System.out.println("NumberFormatException");}catch (RuntimeException ex) {System.out.println("RuntimeException");}}static void method() {String s = "5.6";Integer.parseInt(s); // Cause a NumberFormatExceptionint i = 0;int y = 2 / i;System.out.println("Welcome to Java");}}
The program displays NumberFormatException.
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.
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.
is an instance of RuntimeException or Error.
Unchecked 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 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 }
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.
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
Write an expression to test if a file exists for a File object f.
f.exists()
Write an expression to test if a File object f represents a directory.
f.isDirectory()
Write an expression that tests if a File object f represents a file.
f.isFile()
Write an expression that returns the size of the file for a File object f.
f.length()
Assume that command is a variable of type String. Write a statement that throws an Exception with a message "null command" if command is null.
if (command == null) throw new Exception("null command");
Assume that command is a variable of type String.Write a statement that throws an Exception with a message "null command" if command is null and that throws an Exception with a message "empty command" if command equals the empty string.
if (command == null) throw new Exception("null command"); else if (command.equals("")) throw new Exception("empty command");
Suppose a reference variable of type File called myFile has already been declared. Create an object of type File with the initial file name input.dat and assign it to the reference variable myFile.
myFile = new File ("input.dat");
Assume that maxtries is a variable of type int that has been declared and given a value.Write an expression whose value is a reference to a newly created Exception object whose message is the string "attempt limit exceeded: " followed by the value of maxtries.
new Exception("attempt limit exceeded: " + maxtries)
Write an expression whose value is a reference to a newly created Exception object whose message is "out of oil".
new Exception("out of oil")
Write an expression whose value is a reference to a newly created Exception object with no specific message.
new Exception()
Write an expression that creates a Scanner object for a File object f.
new Scanner(f)
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
Define a public static method named f2s that takes a single String argument, the name of a file.The method returns a (concievably very large!) String that is an exact copy of the contents of the file. If the file cannot be opened the method returns null.
public static String f2s(String fn) { Scanner f = null; try { f = new Scanner(new File(fn)); String s = ""; while (f.hasNextLine()) s += f.nextLine() + "\n"; f.close(); return s; } catch (IOException ex) { if (f != null) f.close(); } return null; }
The method shown below,public void makeJunk(){new File("junk").createNewFile();}generates compile error:"unreported exception java.io.IOException; must be caught or declared to be thrown".Without changing the behavior (any part of the method body) and without changing the number of arguments the function takes or its visibility, add the necessary code that will permit this code to compile without error.
public void makeJunk() throws IOException { new File("junk").createNewFile(); } public void makeJunk() { try { new File("junk").createNewFile(); } catch (IOException e) { } }
Assume that success is a variable of type boolean that has been declared.Assume that processor refers to an object that provides a void method named process that takes no arguments. As it happens, the process method may throw one of several exceptions.Write some code that invokes the process method provided by the object associated with processor and arrange matters so that if any exception is thrown success to be set to false but otherwise it is set to true.Hint: use the catch (Exception ex) for the catch clause.
success = true; try { processor.process(); } catch (Exception e) { success = false; }
What is the keyword for throwing an exception when an exception occurs?
throw
Assume that dataFailure is a variable of type Exception that has been declared and that references an Exception object.Write a statement that throws that Exception object.
throw dataFailure;
What is the keyword for declaring a method for throwing an exception?
throws
Assume that processor refers to an object that provides a void method named process that takes no arguments. As it happens, the process method may throw one of several exceptions.Write some code that invokes the process method provided by the object associated with processor and arrange matters so that your code causes any exception thrown by process to be ignored.Hint: use the catch (Exception ex) and do nothing under the catch clause.
try { processor.process(); } catch (Exception e) { // just ignore the exception }
Assume that processor refers to an object that provides a void method named process that takes no arguments. As it happens, the process method may throw one of several exceptions.Write some code that invokes the process method provided by the object associated with processor and arrange matters so that if process throws any exception, your code prints the message "process failure" to standard output and does nothing else in regard to the exception.Hint: use the catch (Exception ex) for the catch clause.
try { processor.process(); } catch (Exception e) { System.out.println("process failure"); }
Assume that validData is a variable of type boolean that has been declared. Assume that processor refers to an object that provides a void method named process that takes no arguments. As it happens, the process method may throw one of several exceptions, one of which is NumberFormatException.Write some code that invokes the process method provided by the object associated with processor and arrange matters so that any NumberFormatException that is thrown is caught and causes validData to be set to false.Hint: use the catch (Exception ex) for the catch clause.
try { processor.process(); } catch (NumberFormatException nfe) { validData = false; }