Ok, everybody here already know about the affair, I am just discussing some more bits of this love triangle.
Lets dig hard to the shallow level :)
So from even the baddest of our common-sense, we smell that finally block supercedes the two others, viz., try and catch. Lets prove a point in this.
The output will always be 0.
So, basically, I can have a conversation as follows:
Asker: Dude, what you are gonna do with this finally?
Me: Ok dude, since this is the one that will be run no matter how my program logic screws up in the try block, I may write only that part which will not throw any problems like (1+2*3). But I will not. I will not involve my business logic in this love-triangle.
Asker: What then?
Me: I'd love to clear up things only.
Asker: I'm not clear!
Me: For example, if I am doing input-output operations, then I will close the connections in finally and nullify the references to help Mr. GC.
Asker: Ok
Me: Enjoy!
Lets dig hard to the shallow level :)
try{
//try something
}
//and if the trial goes wrong, catch the issue and handle
catch(Exception e){
//handling the problematic part
//or at least letting the program to continue
//and exit gracefully and not shut at face!
}
//but
finally{
//do this, so you are the winner!!
}
So from even the baddest of our common-sense, we smell that finally block supercedes the two others, viz., try and catch. Lets prove a point in this.
class Dodo {
public static void main(String...args) {
int num = doSomething();
System.out.println(num);
}
private static int doSomething() {
try {
return (1+2+3);
}
catch(Exception e) {
return -1;
}
finally {
return 0;
}
}
}
The output will always be 0.
So, basically, I can have a conversation as follows:
Asker: Dude, what you are gonna do with this finally?
Me: Ok dude, since this is the one that will be run no matter how my program logic screws up in the try block, I may write only that part which will not throw any problems like (1+2*3). But I will not. I will not involve my business logic in this love-triangle.
Asker: What then?
Me: I'd love to clear up things only.
Asker: I'm not clear!
Me: For example, if I am doing input-output operations, then I will close the connections in finally and nullify the references to help Mr. GC.
Asker: Ok
Me: Enjoy!
public class TCFTest {
static int i;
public static void main(String[] args) {
m1();
System.out.println(i); //What will be the output? ^_^
}
static void m1(){
//the value of static variable 'i' will be set
try{
i= 1;
try{
i= 4;
}
finally{
i= 5;
}
}
catch(Exception e){
i= 2;
}
finally{
i= 3;
try{
i= 6;
}
finally{
i= 7;
}
}
}//m1() end
}
No comments:
Post a Comment
Liked or hated the post? Leave your words of wisdom! Thank you :)