Java 06 Exceptions
Exception
A Java programmer is developing a desktop application. Which of the following exceptions would be appropriate for him to throw explicitly from his code?
Use ArraryIndexOutOfBoundsException for the catch argument and add code in the catch block to log or print the exception Use flow control to terminate the loop
A new Java programmer has written the following method that takes an array of integers and sums up all the integers that are less than 100. public void processArray(int[] values){ int sum = 0; int i = 0; try{ while(values[i]<100){ sum = sum +values[i]; i++; } } catch(Exception e){ } System.out.println("sum = "+sum); } Which of the following are best practices to improve this code? Each correct answer represents a complete solution. Choose two.
catch, finally or both
A try statement must always have a ............. associated with it.
exceptional conditions external to an application that a well written application should anticipate and from which it can recover
Checked exceptions are meant for...
Change declaration of all the three method to include throws Exception
Consider the following public class TestClass { public static void main(String[] args) { TestClass tc = new TestClass(); tc.myMethod(); } public void myMethod() { yourMethod(); } public void yourMethod() { throw new Exception(); } }
It will not even compile.
Consider the following class : public class Parser{ public static void main( String[] args){ try{ int i = 0; i = Integer.parseInt( args[0] ); } catch(NumberFormatException e){ System.out.println("Problem in " + i ); } } } What will happen if it is run with the following command line: java Parser one
If IOException gets thrown at line1, then the whole method will end up throwing CloneNotSupportedException. If no exception is thrown at linel, then the whole method will end up throwing CloneNotSupportedException
Consider the following code snippet: void m1() throws Exception{ try{ // line1 } catch (IOException e){ throw new SQLException(); } catch(SQLException e){ throw new InstantiationException(); } finally{ throw new CloneNotSupportedException(); // this is not a RuntimeException. } } Which of the following statements are true? Each correct answer represents a complete solution. Choose two
MyException Exception Throwable
Consider the following code... class MyException extends Exception {} public class TestClass{ public void myMethod() throws XXXX{ throw new MyException(); } } What can replace XXXX? Each correct answer represents a complete solution. Choose all that apply.
Doing stuff... Exception in thread "main" java.lang.Exception: Too high! at Test.Class.doStuff(TestClass.java:29) at TestClass.main(TestClass.java:41) Doing stuff... Done stuff. Over
Consider the following code: public class TestClass { public static void doStuff() throws Exception{ System.out.println("Doing stuff..."); if(Math.random()>0.4){ throw new Exception("Too high!"); } System.out.println("Done stuff."); } public static void main(String[] args) throws Exception { doStuff(); System.out.println("Over"); } } Which of the following are possible outputs when the above program is compiled and run? Each correct answer represents a complete solution. Choose all that apply. (Assume that Math.random() returns a double between 0.0 and 1.0 not including 1.0. Further assume that there is no mistake in the line numbers printed in the output shown in the options.)
It will return 10.0
Consider the following method - public float parseFloat( String s ){ float f = 0.0f; try{ f = Float.valueOf( s ).floatValue(); return f ; } catch(NumberFormatException nfe){ f = Float.NaN ; return f; } finally{ f = 10.0f; return f; } } What will it return if the method is called with the input "0.0"?
It will throw a NullPointerException
Consider the following program... class ArrayTest{ public static void main(String[] args){ int ia[][] = { {1, 2}, null }; for (int i = 0; i < 2; i++) for (int j = 0; j < 2; j++) System.out.println(ia[i][j]); } }
If run with no arguments, the program will only print 'The end'. If run with one argument, the program will print 'Exception in Main' and 'The end'.
Considering the following program, which of the options are true? Each correct answer represents a complete solution. Choose all that apply. public class FinallyTest{ public static void main(String args[]){ try{ if (args.length == 0) return; else throw new Exception("Some Exception"); } catch(Exception e){ System.out.println("Exception in Main"); } finally{ System.out.println("The end"); } } }
The code will not compile.
Following is a supposedly robust method to parse an input for a float : public float parseFloat(String s){ float f = 0.0f; try{ f = Float.valueOf(s).floatValue(); return f ; } catch(NumberFormatException nfe){ System.out.println("Invalid input " + s); f = Float.NaN ; return f; } finally { System.out.println("finally"); } return f ; } Which of the following statements about the above method is/are true?
It will print: Automobile: drive Truck: drive Truck: drive in that order.
Given the following classes, what will be the output of compiling and running the class Truck? class Automobile{ public void drive() { System.out.println("Automobile: drive"); } } public class Truck extends Automobile{ public void drive() { System.out.println("Truck: drive"); } public static void main (String args [ ]){ Automobile a = new Automobile(); Truck t = new Truck(); a.drive(); //1 t.drive(); //2 a = t; //3 a.drive(); //4 } }
The program will throw a java.lang.ClassCastException at the line labelled 3 when run. THe cast at line 2 is needed.
Given the following program, which statements are true? // Filename: TestClass.java public class TestClass{ public static void main(String args[]){ A[] a, a1; B[] b; a = new A[10]; a1 = a; b = new B[20]; a = b; // 1 b = (B[]) a; // 2 b = (B[]) a1; // 3 } } class A { } class B extends A { } Each correct answer represents a complete solution. Choose two.
try { for( ;; ); }finally { }
Identify correct constructs.
run()
If a class implements the Runnable interface, which method must a class contain?
that you can use to determine what to do when something unexpected happens. for logging unexpected behavior
Java Exceptions is a mechanism .. Each correct answer represents a complete solution. Choose all that apply.
It allows creation of new exceptions that are custom to a particular application domain. It improves code because error handling code is clearly separated from the main program logic.
Java's Exception mechanism helps in which of the following ways? Each correct answer represents a complete solution. Choose all that apply.
Throwable Exception RuntimeException
Objects of which of the following classes can be thrown using a throw statement? Each correct answer represents a complete solution. Choose all that apply.
For code that should be run regardless of errors
The finally keyword is used for which of the following purposes?
Remove line 3, 6 Remove line 5, 6 Remove line 7 Remove line 3, 7
What can be done to get the following code to compile and run? Each correct answer represents a complete solution. Choose all that apply (Assume that the options are independent of each other.) public float parseFloat( String s ){ float f = 0.0f; // 1 try{ f = Float.valueOf( s ).floatValue(); // 2 return f ; // 3 } catch(NumberFormatException nfe){ f = Float.NaN ; // 4 return f; // 5 } finally { return f; // 6 } return f ; // 7 }
Any class that is-a Throwable
What can be the type of a catch argument?
Exception Error RuntimeException
What class of objects can be declared by the throws clause? Each correct answer represents a complete solution. Choose three
abce An exception with the message set to "3"
What does the output of the following contain? (Choose all that apply.) 12: public static void main(String[] args) { 13: System.out.print("a"); 14: try { 15: System.out.print("b"); 16: throw new IllegalArgumentException(); 17: } catch (IllegalArgumentException e) { 18: System.out.print("c"); 19: throw new RuntimeException("1"); 20: } catch (RuntimeException e) { 21: System.out.print("d"); 22: throw new RuntimeException("2"); 23: } finally { 24: System.out.print("e"); 25: throw new RuntimeException("3"); 26: } 27: }
A event that disrupts the normal flow of instructions during the execution
What is an exception?
AEC
What is printed besides the stack trace caused by the NullPointerException from line 16? class DoSomething { public void go() { System.out.print("A"); try { stop(); } catch (ArithmeticException e) { System.out.print("B"); } finally { System.out.print("C"); } System.out.print("D"); } public void stop() { System.out.print("E"); Object x = null; x.toString(); System.out.print("F"); } public static void main(String[] args) { new DoSomething().go(); } }
1 2 4 The stack trace for a NullPointerException
What is printed by the following? (Choose all that apply.) public class Mouse { public String name; public void run() { System.out.print("1"); try { System.out.print("2"); name.toString(); System.out.print("3"); } catch (NullPointerException e) { System.out.print("4"); throw e; } System.out.print("5"); } public static void main(String[] args) { Mouse jerry = new Mouse(); jerry.run(); System.out.print("6"); } }
Starting up Problem
What is the output of the following program? class Laptop { public void start() { try { System.out.print("Starting up "); throw new Exception(); } catch (Exception e) { System.out.print("Problem "); System.exit(0); } finally { System.out.print("Shutting down "); } } public static void main(String[] args) { new Laptop().start(); } }
12, followed by a stack trace for a NUmberFormatException
What is the output of the following program? public class Cat { public String name; public void parseName() { System.out.print("1"); try { System.out.print("2"); int x = Integer.parseInt(name); System.out.print("3"); } catch (NullPointerException e) { System.out.print("4"); } System.out.print("5"); } public static void main(String[] args) { Cat leo = new Cat(); leo.name = "Leo"; leo.parseName(); System.out.print("6"); } }
The code does not compile
What is the output of the following snippet, assuming a and b are both 0? 3: try { 4: return a / b; 5: } catch (RuntimeException e) { 6: return -1; 7: } catch (ArithmeticException e) { 8: return 0; 9: } finally { 10: System.out.print("done"); 11: }
It fails to compile
What is the result of compiling and running this code? class MyException extends Throwable{} class MyException1 extends MyException{} class MyException2 extends MyException{} class MyException3 extends MyException2{} public class ExceptionTest{ void myMethod() throws MyException{ throw new MyException3(); } public static void main(String[] args){ ExceptionTest et = new ExceptionTest(); try{ et.myMethod(); } catch(MyException me){ System.out.println("MyException thrown"); } catch(MyException3 me3){ System.out.println("MyException3 thrown"); } finally{ System.out.println(" Done"); } } }
There is nothing wrong with the code and Done will be printed.
What is wrong with the following code written in a single file named TestClass.java? class SomeThrowable extends Throwable { } class MyThrowable extends SomeThrowable { } public class TestClass{ public static void main(String args[]) throws SomeThrowable{ try{ m1(); }catch(SomeThrowable e){ throw e; }finally{ System.out.println("Done"); } } public static void m1() throws MyThrowable{ throw new MyThrowable(); } }
It will not compile because of unhandled exception.
What is wrong with the following code? class MyException extends Exception {} public class TestClass{ public static void main(String[] args){ TestClass tc = new TestClass(); try{ tc.m1(); } catch (MyException e){ tc.m1(); } finally{ tc.m2(); } } public void m1() throws MyException{ throw new MyException(); } public void m2() throws RuntimeException{ throw new NullPointerException(); } }
add throws IOException to the main method as well as to PortConnector constructor add throws Exception to PortConnector constructor and change catch(RuntimeException re) to catch(Exception re) in the main method
What two changes can you do, independent of each other, to make the following code compile: //assume appropriate imports class PortConnector { public PortConnector(int port) { if (Math.random() > 0.5) { throw new IOException(); } throw new RuntimeException(); } } public class TestClass { public static void main(String[] args) { try { PortConnector pc = new PortConnector(10); } catch (RuntimeException re) { re.printStackTrace(); } } }
It will print j = 1;
What will be the output of the following class. class Test{ public static void main(String[] args){ int j = 1; try{ int i = doIt() / (j = 2); } catch (Exception e){ System.out.println(" j = " + j); } } public static int doIt() throws Exception { throw new Exception("FORGET IT"); } }
The program will print m1 Starts. The program will print m1 Starts, 1 and 4, in that order. END will not be printed
What will be the output of the following program: Each correct answer represents a complete solution. Choose all that apply public class TestClass{ public static void main(String args[]){ try{ m1(); }catch(IndexOutOfBoundsException e){ System.out.println("1"); throw new NullPointerException(); }catch(NullPointerException e){ System.out.println("2"); return; }catch (Exception e) { System.out.println("3"); }finally{ System.out.println("4"); } System.out.println("END"); } static void m1(){ System.out.println("m1 Starts"); throw new IndexOutOfBoundsException( "Big Bang " ); } }
try finally out
What will be the output of the following program? class TestClass{ public static void main(String[] args) throws Exception{ try{ amethod(); System.out.println("try"); } catch(Exception e){ System.out.println("catch"); } finally { System.out.println("finally"); } System.out.println("out"); } public static void amethod(){ } }
It will print E1 and Finally.
What will be the output when the following code is compiled and run? //in file Test.java class E1 extends Exception{ } class E2 extends E1 { } class Test{ public static void main(String[] args){ try{ throw new E2(); } catch(E1 e){ System.out.println("E1"); } catch(Exception e){ System.out.println("E"); } finally{ System.out.println("Finally"); } } }
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10 at exceptions.TestClass.doTest(TestClass.java:24) at exceptions.TestClass.main(TestClass.java:14)
What will be the output when the following program is run? package exceptions; public class TestClass { public static void main(String[] args) { try{ doTest(); } catch(MyException me){ System.out.println(me); } } static void doTest() throws MyException{ int[] array = new int[10]; array[10] = 1000; doAnotherTest(); } static void doAnotherTest() throws MyException{ throw new MyException("Exception from doAnotherTest"); } } class MyException extends Exception { public MyException(String msg){ super(msg); } }
exceptions.MyException: Exception from foo
What will be the output when the following program is run? package exceptions; public class TestClass{ public static void main(String[] args) { try{ hello(); } catch(MyException me){ System.out.println(me); } } static void hello() throws MyException{ int[] dear = new int[7]; dear[0] = 747; foo(); } static void foo() throws MyException{ throw new MyException("Exception from foo"); } } class MyException extends Exception { public MyException(String msg){ super(msg); } } (Assume that line numbers printed in the messages given below are correct.)
The code will fail to compile
What will be the result of attempting to compile and run the following program?
No compilation error and line 3 will be executed.
What will be the result of attempting to compile and run the following program? class TestClass{ public static void main(String args[]){ int i = 0; loop : // 1 { System.out.println("Loop Lable line"); try{ for ( ; true ; i++ ){ if( i >5) break loop; // 2 } } catch(Exception e){ System.out.println("Exception in loop."); } finally{ System.out.println("In Finally"); // 3 } } } }
The program will compile without error and will print java.lang.NullPointerException when run.
What will be the result of attempting to compile and run the following program? public class TestClass{ public static void main(String args[]){ try{ RuntimeException re = null; throw re; } catch(Exception e){ System.out.println(e); } } }
It will not compile
What will be the result of compiling and running the following program? class NewException extends Exception {} class AnotherException extends Exception {} public class ExceptionTest{ public static void main(String[] args) throws Exception{ try{ m2(); } finally{ m3(); } catch (NewException e){} } public static void m2() throws NewException { throw new NewException(); } public static void m3() throws AnotherException{ throw new AnotherException(); } }
It will compile but will throw AnotherException when run.
What will be the result of compiling and running the following program? class NewException extends Exception {} class AnotherException extends Exception {} public class ExceptionTest{ public static void main(String [] args) throws Exception{ try{ m2(); } finally{ m3(); } } public static void m2() throws NewException{ throw new NewException(); } public static void m3() throws AnotherException{ throw new AnotherException(); } }
It will run and throw an arithmeticException.
What will happen if you add the statement System.out.println(5 / 0); to a working main() method?
It will throw ExceptionInInitializerError at runtime
What will happen when the following code is compiled and run? class AX{ static int[] x = new int[0]; static{ x[0] = 10; } public static void main(String[] args){ AX ax = new AX(); } }
It will throw NullPointerException
What will happen when the following program is compiled and run? public class SM{ public String checkIt(String s){ if(s.length() == 0 || s == null){ return "EMPTY"; } else return "NOT EMPTY"; } public static void main(String[] args){ SM a = new SM(); System.out.println(a.checkIt(null)); } }
It will compile without any warning but will throw a runtime exception.
What will happen when you compile and execute the following code? import java.util.*; class Pregen { public static void main(String args[]) { List<Object> list = new ArrayList<Object>(); list.add("Str "); list.add(new Integer(2)); System.out.print(list.get(1)); System.out.print(list.get(2)); } }
It will compile successfully but will throw an exception at runtime.
What will happen when you try to compile and execute the following code? import java.util.*; class FormatPercent { public static void main(String args[]) { System.out.format("Percent = %d%%",50.2); } }
99, 11
What will the following class print? class Test{ public static void main(String[] args){ int[][] a = { { 00, 01 }, { 10, 11 } }; int i = 99; try { a[val()][i = 1]++; } catch (Exception e) { System.out.println( i+", "+a[1][1]); } } static int val() throws Exception { throw new Exception("unimplemented"); } }
It will print calculating and then throw NullPointerException
What will the following code print when compiled and run? abstract class Calculator{ abstract void calculate(); public static void main(String[] args){ System.out.println("calculating"); Calculator x = null; x.calculate(); } }
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 at ExceptionTest.doSomething(ExceptionTest.java:12) at ExceptionTest.main(ExceptionTest.java:4)
What will the following code print when compiled and run? (Assume that MySpecialException is an unchecked exception.) 1. public class ExceptionTest { 2. public static void main(String[] args) { 3.try { 4. doSomething(); 5.} catch (MySpecialException e) { 6. System.out.println(e); 7.} 8. } 9. 10. static void doSomething() { 11.int[] array = new int[4]; 12.array[4] = 4; 13.doSomethingElse(); 14. } 15. 16. static void doSomethingElse() { 17.throw new MySpecialException("Sorry, can't do something else"); 18. } }
1
What will the following code print when run? public class Test { static String s = ""; public static void m0(int a, int b) { s += a; m2(); m1(b); } public static void m1(int i) { s += i; } public static void m2() { throw new NullPointerException("aa"); } public static void m() { m0(1, 2); m1(3); } public static void main(String args[]) { try { m(); } catch (Exception e) { } System.out.println(s); } }
400
What will the following code print? public class Test{ public int luckyNumber(int seed){ if(seed > 10) return seed%10; int x = 0; try{ if(seed%2 == 0) throw new Exception("No Even no."); else return x; } catch(Exception e){ return 3; } finally{ return 7; } } public static void main(String args[]){ int amount = 100, seed = 6; switch( new Test().luckyNumber(6) ){ case 3: amount = amount * 2; case 7: amount = amount * 2; case 6: amount = amount + amount; default : } System.out.println(amount); } }
It will not print anything.
What will the following program print when run? public class TestClass{ public static void main(String[] args){ try{ System.exit(0); } finally{ System.out.println("finally is always executed!"); } } }
When there are no catch blocks in a try statement.
When are you required to use a finally block in a regular try statement (not a try-withresources)?
Run-time
When do exceptions are thrown inside the Java classes themselves?
finally
Which block always executes whether an exception is thrown or not?
Exception
Which class should be the superclass of any exception that you create in Java?
1 2 3
Which code fragments will print the last argument given on the command line to the standard output, and exit without any output or exception stack trace if no arguments are given? Each correct answer represents a complete solution. Choose three 1. public static void main(String args[ ]){ if (args.length != 0) System.out.println(args[args.length-1]); } 2.public static void main(String args[ ]){ try { System.out.println(args[args.length-1]); } catch (ArrayIndexOutOfBoundsException e) { } } 3. public static void main(String args[ ]){ int i = args.length; if (i != 0) System.out.println(args[i-1]); } 4.public static void main(String args[ ]){ int i = args.length-1; if (i > 0) System.out.println(args[i]); } 5. public static void main(String args[ ]){ try { System.out.println(args[args.length-1]); } catch (NullPointerException e) {} }
The program will print 1, 4 and 5, in that order.
Which digits and in what order will be printed when the following program is run? public class TestClass{ public static void main(String args[]){ int k = 0; try{ int i = 5/k; } catch (ArithmeticException e){ System.out.println("1"); } catch (RuntimeException e){ System.out.println("2"); return ; } catch (Exception e){ System.out.println("3"); } finally{ System.out.println("4"); } System.out.println("5"); } }
Exception
Which exact exception class will the following class throw when compiled and run? class Test{ public static void main(String[] args) throws Exception{ int[] a = null; int i = a [ m1() ]; } public static int m1() throws Exception{ throw new Exception("Some Exception"); } }
NumberFormatException
Which exception is a subclass of IllegalArgumentException?
ClassCastException
Which exception will the following throw? Object obj = new Integer(3); String str = (String) obj; System.out.println(str);
return
Which keyword is used to jump out of the try block into the finally block?
throw
Which keyword is used to throw any exception explicitly
java.io.FileNotFoundException java.lang.SecurityException
Which of the following are standard Java exception classes? Each correct answer represents a complete solution. Choose two.
Checked exceptions are required to be handled or declared. Errors are allowed to be handled or declared. Runtime exceptions are allowed to be handled or declared.
Which of the following are true? (Choose all that apply.)
ArrayIndexOutOfBoundsException IllegalArgumentException NumberFormat Exception Any exception that extends RuntimeException
Which of the following are unchecked exceptions? (Choose all that apply.)
try-finally-catch
Which of the following blocks is not used to handle the exception
public void roar(){} public void roar() throws HasSoreThroatException{} public void roar() throws IllegalArguementException{} public void roar() throws TiredException{}
Which of the following can be inserted into Lion to make this code compile? (Choose all that apply.) class HasSoreThroatException extends Exception {} class TiredException extends RuntimeException {} interface Roar { void roar() throws HasSoreThroatException; } class Lion implements Roar {// INSERT CODE HERE }
System.out.println("It's ok"); throw new IllegalArguemtnException(); throw new java.io.IOException(); throw new RuntimeException();
Which of the following can be inserted on line 8 to make this code compile? (Choose all that apply) 7: public void ohNo() throws IOException { 8: // INSERT CODE HERE 9: }
Class
Which of the following categories does an exception belong to?
IOException
Which of the following exception classes is defined by the java.io package?
ArraryIndexOutOfBoundsException ExceptionInInitializerError NullPointerException
Which of the following exceptions are thrown by the JVM (Choose all that apply.)
ArithmeticException
Which of the following exceptions is thrown in the given code? class Main { public static void main(String args[]) { int x = 0; int y = 10; int z = y/x; } }
FileNotFoundException
Which of the following is not a runtime exception?
Throwable
Which of the following is the parent class of all Exception classes?
catch
Which of the following keywords handles exceptions thrown by the try block?
throw
Which of the following keywords throws an exception object inside a method?
NullPointerException IllegalArgumentException RuntimeException
Which of the following options will you use to fill the blank to successfully compile the code? Each correct answer represents a complete solution. Choose three. public static int getLength(String s) { if (s == null) throw new ________("The argument cannot be null"); return s.length(); }
On line 7, fill in throws On line 8, fill in throw new
Which of the following pairs fill in the blanks to make this code compile? (Choose all that apply.) 7: public void ohNo() _____ Exception { 8: _____________ Exception(); 9: }
java.lang.SecurityException java.lang.ClassCastException java.lang.NullPointerException java.lang.IndexOutOfBoundsException
Which of the following standard java exception classes extend java.lang.RuntimeException Each correct answer represents a complete solution. Choose all that apply.
A keyword used to raise an exception to JVM explicitly
Which of the following statements correctly specifies the throw keyword?
try
Which of the following statements encloses a block of code in which an exception is likely to occur?
The main method of a program can declare that it throws checked exceptions. A method declaring that it throws a certain exception class may throw instances of any subclass of that exception class.
Which of these statements are true? Each correct answer represents a complete solution. Choose all that apply.
An unexpected parameter is passed into a method.
Which scenario is the best use of an exception?
Declare IOException in the throws clause of your method Wrap the call to another method within a try-catch block that catches Exception.
You have a method that currently does not handle any exception thrown from the code contained in its method body. You are now changing this method to call another method that throws IOException. What changes, independent of each other, can you make to your method so that it will compile? Each correct answer represents a complete solution. Choose two.