谜题36:优柔寡断

下面的程序打印的是什么呢?甚至,它是合法的吗?
  1. publicclassIndecisive{
  2. publicstaticvoidmain(String[]args){
  3. System.out.println(decision());
  4. }
  5. staticbooleandecision(){
  6. try{
  7. returntrue;
  8. }finally{
  9. returnfalse;
  10. }
  11. }
  12. }
这个程序会打印false。我是这么理解的,在try catch里面如果有return,则它会为返回值准备好位置,并把值放进去。如果finally里面也有return,它会覆盖返回值位置上的值。

谜题37:极端不可思议

下面的三个程序每一个都会打印些什么?不要假设它们都可以通过编译。
  1. importjava.io.IOException;
  2. publicclassArcane1{
  3. publicstaticvoidmain(String[]args){
  4. try{
  5. System.out.println("Helloworld");
  6. }catch(IOExceptione){
  7. System.out.println("I'veneverseenprintlnfail!");
  8. }
  9. }
  10. }
  11. publicclassArcane2{
  12. publicstaticvoidmain(String[]args){
  13. try{
  14. //Ifyouhavenothingnicetosay,saynothing
  15. }catch(Exceptione){
  16. System.out.println("Thiscan'thappen");
  17. }
  18. }
  19. }
  20. interfaceType1{
  21. voidf()throwsCloneNotSupportedException;
  22. }
  23. interfaceType2{
  24. voidf()throwsInterruptedException;
  25. }
  26. interfaceType3extendsType1,Type2{
  27. }
  28. publicclassArcane3implementsType3{
  29. publicvoidf(){
  30. System.out.println("Helloworld");
  31. }
  32. publicstaticvoidmain(String[]args){
  33. Type3t3=newArcane3();
  34. t3.f();
  35. }
  36. }
第一个程序不能通过编译, 因为catch捕获的是一个checked exception,而try里面并没有语句抛出checked exception,这是不行的。
第二个程序能通过编译,但不会打印任何东西。虽然try里面没有抛出任何异常,但捕获unchecked exception是可以的。
第三个程序可以打印Hello World。这里涉及到子类在复写方法的时候需要怎么处理父类声明的Exception问题。子类只是不可以扩大父类声明的Exception范围。

谜题38:不受欢迎的宾客

本谜题中的程序所建模的系统,将尝试着从其环境中读取一个用户ID,如果这种尝试失败了,则缺省地认为它是一个来宾用户。该程序的作者将面对有一个静态域的初始化表达式可能会抛出异常的情况。因为Java不允许静态初始化操作抛出被检查异常,所以初始化必须包装在try-finally语句块中。那么,下面的程序会打印出什么呢?
  1. publicclassUnwelcomeGuest{
  2. publicstaticfinallongGUEST_USER_ID=-1;
  3. privatestaticfinallongUSER_ID;
  4. static{
  5. try{
  6. USER_ID=getUserIdFromEnvironment();
  7. }catch(IdUnavailableExceptione){
  8. USER_ID=GUEST_USER_ID;
  9. System.out.println("Logginginasguest");
  10. }
  11. }
  12. privatestaticlonggetUserIdFromEnvironment()
  13. throwsIdUnavailableException{
  14. thrownewIdUnavailableException();
  15. }
  16. publicstaticvoidmain(String[]args){
  17. System.out.println("UserID:"+USER_ID);
  18. }
  19. }
  20. classIdUnavailableExceptionextendsException{
  21. }
本程序不能通过编译,编译器会提示:variable USER_ID might already have been assigned
对于final的变量,编译器很难确定它是否已经被赋值了。除非它明确地看到没有赋值的地方。

谜题39:您好,再见!

下面的程序打印什么?
  1. publicclassHelloGoodbye{
  2. publicstaticvoidmain(String[]args){
  3. try{
  4. System.out.println("Helloworld");
  5. System.exit(0);
  6. }finally{
  7. System.out.println("Goodbyeworld");
  8. }
  9. }
  10. }
它不会说再见,System.exit(0)方法将停止当前线程和所有其他当场死亡的线程. 也就是说finally级别没有它高。但是,你可以通过addShutdownHook来做一些exit之前必须处理的事情:
  1. publicclassHelloGoodbye1{
  2. publicstaticvoidmain(String[]args){
  3. System.out.println("Helloworld");
  4. Runtime.getRuntime().addShutdownHook(
  5. newThread(){
  6. publicvoidrun(){
  7. System.out.println("Goodbyeworld");
  8. }
  9. });
  10. System.exit(0);
  11. }
  12. }

谜题40:不情愿的构造器

尽管在一个方法声明中看到一个throws子句是很常见的,但是在构造器的声明中看到一个throws子句就很少见了。下面的程序就有这样的一个声明。那么,它将打印出什么呢?
  1. publicclassReluctant{
  2. privateReluctantinternalInstance=newReluctant();
  3. publicReluctant()throwsException{
  4. thrownewException("I'mnotcomingout");
  5. }
  6. publicstaticvoidmain(String[]args){
  7. try{
  8. Reluctantb=newReluctant();
  9. System.out.println("Surprise!");
  10. }catch(Exceptionex){
  11. System.out.println("Itoldyouso");
  12. }
  13. }
  14. }
这个题目的标题和说明性的文字有点迷惑你,实际上这个程序的问题和构造函数里面抛异常没有关系。它和下面是等价的:
  1. publicclassReluctant{
  2. privateReluctantinst=newReluctant();
  3. publicstaticvoidmain(String[]args){
  4. Reluctantr=newReluctant();
  5. }
  6. }
这个程序因为他有一个私有成员变量,私有成员变量在初始化的时候会调用构造函数,然而这一过程会一直递归调用下去,直到StackOverflowError。

谜题41:域和流

这个程序试图把数据从源文件流拷贝到目标文件流,然后关闭所有它打开的流,哪怕它遇到异常。它能正常处理吗?
  1. staticvoidcopy(Stringsrc,Stringdest)throwsIOException{
  2. InputStreamin=null;
  3. OutputStreamout=null;
  4. try{
  5. in=newFileInputStream(src);
  6. out=newFileOutputStream(dest);
  7. byte[]buf=newbyte[1024];
  8. intn;
  9. while((n=in.read(buf))>0)
  10. out.write(buf,0,n);
  11. }finally{
  12. if(in!=null)in.close();
  13. if(out!=null)out.close();
  14. }
  15. }
这个程序这样的写法,是我以前喜欢的做法, 但自从工作中发生了一次事故之后,我再也不这样写了。当时我也在finally里面做一些其他连接的清理工作,然后关闭数据库连接池,程序结构和上面一样。后来这个程序出了大问题, 每当它运行几天之后,就抛错说连接池已经被用光。 问题出在那些清理工作抛出了新的异常,这个程序的debug也是很艰难的,因为不是每次都会抛异常。或者说只有在一定条件下才会。
对于稀缺资源,比如连接池,流,像下面这样关闭他们,几乎是必须的。
  1. finally{
  2. if(in!=null){
  3. try{
  4. in.close();
  5. }catch(IOExceptionex){
  6. //Thereisnothingwecandoifclosefails
  7. }
  8. if(out!=null)
  9. try{
  10. out.close();
  11. }catch(IOExceptionex){
  12. //Thereisnothingwecandoifclosefails
  13. }
  14. }
  15. }

谜题42:异常为循环而抛

下面的程序大意是,对多维数组中的每一个数组,检查他们是否满足thirdElementIsThree这个规则。下面的程序正确吗?
  1. publicclassLoop{
  2. publicstaticvoidmain(String[]args){
  3. int[][]tests={{6,5,4,3,2,1},{1,2},
  4. {1,2,3},{1,2,3,4},{1}};
  5. intsuccessCount=0;
  6. try{
  7. inti=0;
  8. while(true){
  9. if(thirdElementIsThree(tests[i++]))
  10. successCount++;
  11. }
  12. }catch(ArrayIndexOutOfBoundsExceptione){
  13. //Nomoreteststoprocess
  14. }
  15. System.out.println(successCount);
  16. }
  17. privatestaticbooleanthirdElementIsThree(int[]a){
  18. returna.length>=3&a[2]==3;
  19. }
  20. }
这个程序犯了3个错误:
1 用了恐怖的while(true)作循环;
2 用catch Exception来做为退出循环的条件;

3 错误地使用了&;

谜题43:异常地危险

请写出一个程序, 程序里面会抛出没有被catch住的checked exception, 但是不会被编辑器拒绝.
有两种方法可以实现, 1是利用了Class.newInstance方法, 该方法会调用无参的构造函数, 如果该构造函数抛出checked exception的话, 编译器是检测不到的.

  1. publicclassThrower{
  2. publicThrower()throwsIOException{
  3. thrownewIOException();
  4. }
  5. publicstaticvoidmain(String[]args)
  6. throwsInstantiationException,IllegalAccessException{
  7. Throwerthrower=Thrower.class.newInstance();
  8. }
  9. }
Class.newInstance的文档继续描述道“Constructor.newInstance方法通过将构造器抛出的任何异常都包装在一个(受检查的)InvocationTargetException异常中而避免了这个问题.
第二种方式是利用了泛型.
  1. classTigerThrower<TextendsThrowable>{
  2. publicstaticvoidsneakyThrow(Throwablet){
  3. newTigerThrower<Error>().sneakyThrow2(t);
  4. }
  5. privatevoidsneakyThrow2(Throwablet)throwsT{
  6. throw(T)t;
  7. }
  8. publicstaticvoidmain(String[]args){
  9. sneakyThrow(newIOException());
  10. }
  11. }

谜题45:令人疲惫不堪的测验

本谜题将测试你对递归的了解程度。下面的程序将做些什么呢?

  1. publicclassWorkout{
  2. publicstaticvoidmain(String[]args){
  3. workHard();
  4. System.out.println("It'snaptime.");
  5. }
  6. privatestaticvoidworkHard(){
  7. try{
  8. workHard();
  9. }finally{
  10. workHard();
  11. }
  12. }
  13. }
如果说没有try finally, 他就是一个简单的递归调用,直到StackOverflowError. 但是try finally把问题搞复杂了.
Java虚拟机对栈的深度限制到了某个预设的水平。当超过这个水平时,VM就抛出StackOverflowError。为了让我们能够更方便地考虑程序的行为,我们假设栈的深度为3,这比它实际的深度要小得多。现在让我们来跟踪其执行过程。
main方法调用workHard,而它又从其try语句块中递归地调用了自己,然后它再一次从其try语句块中调用了自己。在此时,栈的深度是3。当workHard方法试图从其try语句块中再次调用自己时,该调用立即就会以StackOverflowError而失败。这个错误是在最内部的finally语句块中被捕获的,在此处栈的深度已经达到了3。在那里,workHard方法试图递归地调用它自己,但是该调用却以StackOverflowError而失败。这个错误将在上一级的finally语句块中被捕获,在此处站的深度是2。该finally中的调用将与相对应的try语句块具有相同的行为:最终都会产生一个StackOverflowError。这似乎形成了一种模式,而事实也确实如此。
Java谜题畅读版之异常谜题

那么,究竟大到什么程度呢?有一个快速的试验表明许多VM都将栈的深度限制为1024,因此,调用的数量就是1+2+4+8…+21,024=2^1,025-1,而抛出的异常的数量是2^1,024。假设我们的机器可以在每秒钟内执行1010个调用,并产生1010个异常,按照当前的标准,这个假设的数量已经相当高了。在这样的假设条件下,程序将在大约1.7×10291年后终止。为了让你对这个时间有直观的概念,我告诉你,我们的太阳的生命周期大约是1010年,所以我们可以很确定,我们中没有任何人能够看到这个程序终止的时刻。尽管它不是一个无限循环,但是它也就算是一个无限循环吧。

原文地址:http://blog.csdn.net/sunxing007/article/details/9090319

相关文章:

  • 2021-08-25
  • 2021-06-17
  • 2022-12-23
  • 2021-09-01
  • 2022-12-23
  • 2021-12-01
猜你喜欢
  • 2021-08-02
  • 2022-01-10
  • 2021-08-12
  • 2021-08-09
  • 2021-07-04
  • 2021-11-27
  • 2022-01-18
相关资源
相似解决方案