File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

NullPointerException problem

 
Travis Benning
Ranch Hand
Posts: 74
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey all,
I saw this on a no-name mock someone sent me.
StringBuffer sb = new StringBuffer();
try {
sb.append("1");
somemethod();
sb.append("2");
}
catch(Exception a) {
sb.append("3");
}
finally{
sb.append("4");}
sb.append("5");
What is the value of "sb" if somemethod()throws NullPointerException.
Answer = 1345.
I thought it would be 134 since "5" is outside the finally block.
Can someone explain this to me.
If I'm wrong, explain to me how.
If I'm right, explain to me how they could get this answer. possible typo or missing varialble or something.
All help is appreciated,
Travis B.
 
Jose Botella
Ranch Hand
Posts: 2120
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
After the catch clause is executed (and the exception is caught), finally is executed too. Then the sentences after finally are executed.
 
Travis Benning
Ranch Hand
Posts: 74
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i thought that if an exception was caught, you get what came before exception, what is included in the catch block, and what is included in the finally block.
I thought that what came after finally was never reached.
 
Jessica Sant
Sheriff
Posts: 4313
Android IntelliJ IDE Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Travis Benning:
i thought that if an exception was caught, you get what came before exception, what is included in the catch block, and what is included in the finally block.
I thought that what came after finally was never reached.

You got it just a little mixed up :
If an exception is handled by a catch block, then the finally block is executed (if present) and execution begins again on the first line after the block.
If an exception is not handled by a catch block, then the finally block is execute (if present) and exception percolates itself up the execution stack. -- the lines after the block are not executed
[ April 26, 2002: Message edited by: Jessica Sant ]
 
Travis Benning
Ranch Hand
Posts: 74
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah. I see
Ok, makes sense now.
Much thanks Jose and Jessica.
Travis B.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic