Chapter6: Exceptions Flashcards
1
Q
What should be added at line 2 for the code to compile? public class Program{ public static void main(String [] args) { // 2 new Program().doIt(); new Program().didIt(); } static void doit()throws java.io.IOException { throw new java.io.IOException(); } static void doit()throws ClassNotFoundException { throw new SecurityException(); } }
A
public static void main(String [] args) throws java.io.IOException, ClassNotFoundException {
these are checked exceptions meaning that they should be declared or handled in a try/catch block.
2
Q
What will be the output of this program when run with the command java Program 10? public class Program{ static Integer I; public static void main(String [] args) { String s; try{ s = I.toString(); } finally { try{ int i = Integer.parseInt(args[0]); } catch (NumberFormatException E) { System.out.print("NumberFormat"); } finally { System.out.print("Fin2"); } System.out.print("Fin1"); } } }
A
Fin 2 Fin 1 followed by uncaught exception
A NullPointer is generated as we try to invoke toString method on a null reference. however there is no catch block to catch it. finally executes and prints fin2. fin 1 is then printed and the NullPointer remains uncaught and thus is thrown at the end.