Given the code fragment:
public static void main(String[] args) { try {
int num = 10;
int div = 0;
int ans = nim / div;
} catch (ArithmeticExeption ae) {
ans = 0 // line nl
} catch (Exception e) {
System.out.println("Invalid calculation");
}
System.out.println("Answer = " + ans); // line n2
)
What is the result?
A. Answer =0
B. Invalid calculation
C. Compilation fails only atline n1.
D. Compilation fails only atline n2.
E. Compilation fails only atline n1 andline2
E :
# javac Test47.java
Test47.java:8: error: cannot find symbol
ans =0; //line n1
^
symbol: variable ans
location: class Test47
Test47.java:13: error: cannot find symbol
System.out.println(“Answer = ” + ans); //line n2
^
symbol: variable ans
location: class Test47
2 errors
Answer E:
The reason is because the variable “ans” is a local variable within the try block only. To solve this problem, just declare int ans above the try block, and remove the type “int” before the “ans” in the try block.
Correct Answer: E