0

Why is Option 2 the correct answer?

And why is B and D not printed? Kind of clueless as to what's going on in this code😥 public class X { public static void main(String □ args) { try { bad Method(){ System. out. pri nt("A"); }catch (Exception ex) { System.out.print("B"); }finally { System. out. print("C"); } System .out. print("D"); } public static void badMethod() { throw new Error(); } } Options: 1. ABCD 2. C is printed before exiting with an error message. 3. Compilation fails 4. BC is printed before exiting with an error message.

23rd Dec 2018, 2:39 PM
Asirap
3 Respostas
+ 3
Let me try. First, try-catch-finally is getting an error in try area. (An Error() belongs to Throwable() and not to Exception?)- because of that the finally area is continuing. But the badMetjod() is thrown an real Error what caused a stop of the code. D can’t be printed because it would follow after the method badMethod(). See also: public class X { public static void main(String[] args) { try { badMethod(); System.out.print("A"); }catch (Exception ex) { System.out.print("B"); }finally { System.out.print("C"); } System.out.print("D"); } public static void badMethod() { throw new Error("Help"); } }
23rd Dec 2018, 9:29 PM
Ronny Ruhe
Ronny Ruhe - avatar
+ 3
hi, badMethod() is trhrowing an error bc of calling it in the try area. after that, there may not be any other code in the try area otherwise an error will be trown. Does it help to understand? Greetz
23rd Dec 2018, 3:18 PM
Ronny Ruhe
Ronny Ruhe - avatar
0
Ronny Ruhe thank you! can you tell me why D is not printed? It is out of the try catch block
23rd Dec 2018, 3:38 PM
Asirap