日期:2014-05-20  浏览次数:20932 次

关于try catch finally,请详解
如果方法methedA()抛出一个IOException,程序的执行结果是?
class ExceptionTest{
 public static void main(String args[]){

  try{methodA();}
  catch(IOException e){
  System.out.println("caught IOException");
  }
  catch(Exception e){
  System.out.println("caught Exception");
  return;
  }
  finally{
  System.out.println("catch one exception");
  }
}

}
A caught IOException catch one exception
B caught IOException caught Exception
C caught Exception catch one exception
D caught Exception caught IOException catch One Exception

------解决方案--------------------
A
java的异常捕捉只要走到一个catch就不会走别的catch了
你的methedA()既然抛出了一个IOException,就会走到第一个catch block,然后到finally。
最后要注意的是,只要执行了try不论有没有异常,不论有没有catch到,都会执行finally中的语句
------解决方案--------------------
A 楼上说得很全
给你测试代码你自己debug跑跑看

Java code

import java.io.IOException;

class ExceptionTest {
    public static void main(String args[]) {

        try {
            methodA();
        } catch (IOException e) {
            System.out.println("caught IOException");
        } catch (Exception e) {
            System.out.println("caught Exception");
            return;
        } finally {
            System.out.println("catch one exception");
        }
    }

    private static void methodA() throws IOException{

        throw new IOException("error");
    }

    
}

------解决方案--------------------
探讨

第一个catch语句那有个红叉,编译提示的错误如下:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unreachable catch block for IOException. This exception is never thrown from the try statemen……