Tuesday, December 29, 2009

Java Exceptions : Interesting questions

Questions

1]
public static void main(String[] args) {
System.out.println(method());
}

public static String method() {
try {
return "Try";
} catch (Exception e) {
return "Cacth";
} finally {
return "Finally";
}
}

2. public static void main(String[] args) {try {
System.out.println(method());
} catch (Exception e) {
System.out.println("CATCH");
}
System.out.println("HELLO");
}

public static int method() throws Exception {
try {
throw new Exception();
} catch (Exception e) {
throw new Exception();
} finally {
return 3;
}
}

3
public class Lab {
static int i = 0;
public static void main(String args[]) throws Exception{
System.out.println(method());
}
public static int method(){
try{
return ++i;
}
finally{
++i;
System.out.println(i);
}
}
}

4.public class Lab extends ABC {

Lab() throws Exception {

System.out.println("Lab Class");
}

Lab(int i) {
System.out.println("inti");
}

public static void main(String[] args) throws Exception {
Lab t = new Lab(12);

}
}
class ABC {
ABC() throws Exception {
System.out.println("ABC Class");
}
}


5.
public class Lab extends ABC {

public void method() throws Exception{
System.out.println("Subclass");
}
public static void main(String args[]) throws Exception{
ABC a = new ABC();
a.method();
Lab l = new Lab();
l.method();
}
}
class ABC {
public void method() throws IOException{
System.out.println("Superclass");
}

}

Answers
1.
 

Finally
2.
Output


3
HELLO

Explanation : A return in finally will suppress the return/exception in try/catch blocks.If there is no return in the finally block , then the return/catch in the try or catch block will be executed after the finally block is executed.

3
Output
2
1
Explanation:The return in the try is executed[but not returned].After exectuing the finally block, the vaule computed in the try is returned not the one from finally.

4. Compilation Error
This will call the ABC constructor implicitly.So the Exception has be to declared to be thrown

5. Compilation error here.
Error: method method() in class prjlab.Lab cannot override method method() in class prjlab.ABC, overridden method does not throw class java.lang.Exception

So change the public void method() throws Exception to
public void method() throws IOException

No comments: