Some Java things in a book

Posted on 2010-03-09 10:16 cjcj 阅读(1246) 评论(0)  编辑  收藏

-Latest I have read a book about java,there are some events which we should care about...So there are some staff here.

  Staff 1:Stricken Testing

    this staff testing how do you know about recursion,so the follow program will do what?

public class Workout {
public static void main(String[] args) {
       workHard();
       System.out.println(
"It's nap time.");
}
private static void workHard() {
try {
    workHard();
   } 
finally {
  workHard();
}
}
}

If there is no try-finally statement,the program behavior will be very clear: workhard method recursively call it own until the program throws StackOverflowError exception,it does not catch the exception to the end.However,try-finally statement make things complicated.When the program throws StackOverflowError,it will be in the finally block of workhand terminated.In this way,it recusively calls itself.It looks like an infinite-looping indeed,but is it really an infinite-looping?If you run it ,it seems really do it just you suppose.but the only way to confirm it is going to analyse its action.

Staff 2 Domain Problem
   Let's see some codes first.

 

static void copy(String src, String dest) throws IOException {
InputStream in 
= null;
OutputStream out 
= null;
try {
    in 
= new FileInputStream(src);    
    out 
= new FileOutputStream(dest);
    
byte[] buf = new byte[512];
    
int n;
    
while ((n = in.read(buf)) > 0)
    out.write(buf, 
0, n);
    } 
finally {
        
if (in != null) in.close();
        
if (out != null) out.close();
    }
}

 
You see,this process looks like all right.All streams initialized to null,and once new stream created,they immediately set new values.If they not null,the finally block will help closing it even happened a exception.the finally block will be excuted before the method returns.So what is wrong here?
    The problem is the finally block itself,closing stream may also throw an excpeiton.If it happened on 'in' stream,the exception will be result in that 'out' stream will never be closed so that the out stream remains in the activity!!

To be continuing...


只有注册用户登录后才能发表评论。


网站导航: