• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

a question about exception?

 
michael wang
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
StringBuffer b=new StringBuffer();
try{
b.append("1");
method();
b.append("2");
}
catch(Exception a){
b.append("3");
}
finally{
b.append("4");
}
b.append("5");
what will be the value of ' b' if the method throws NullPointerException?
is the answer 134?
 
qunlbao leon
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think the answer should be '1345'
the mothed will cause NullPointerException and
it will be catch in the catch block so b.append(2)
will not be executed.
 
michael wang
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
will b.append("5") run?
 
Ajith Kallambella
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The answer will be 1345.
Since the Exception is being caught, the catch{} block will be run, where "2" gets appended.
The finally block will be run anyway, so "4" gets appended.
The exception is caught and handled by this time. Hence the last line will be run, so "5" gets appended.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic