| Author |
NullPointerException problem
|
Travis Benning
Ranch Hand
Joined: Jan 24, 2002
Posts: 74
|
|
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.
|
Sun Certified Programmer for Java 2 Platform
|
 |
Jose Botella
Ranch Hand
Joined: Jul 03, 2001
Posts: 2120
|
|
|
After the catch clause is executed (and the exception is caught), finally is executed too. Then the sentences after finally are executed.
|
SCJP2. Please Indent your code using UBB Code
|
 |
Travis Benning
Ranch Hand
Joined: Jan 24, 2002
Posts: 74
|
|
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
Joined: Oct 17, 2001
Posts: 4313
|
|
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 ]
|
- Jess
Blog:KnitClimbJava | Twitter: jsant | Ravelry: wingedsheep
|
 |
Travis Benning
Ranch Hand
Joined: Jan 24, 2002
Posts: 74
|
|
Ah. I see Ok, makes sense now. Much thanks Jose and Jessica. Travis B.
|
 |
 |
|
|
subject: NullPointerException problem
|
|
|