2011-07-15 39 views
2

你好,Java的捕捉异常和subclases

在Java中,如果像BufferedReader.read()的方法说,它可以抛出一个IOException,我试图抓住一个FileNotFoundException,并在两个catch块的IOException,什么catch块会如果进入文件不存在?

它只输入最具体还是两者?

回答

6

将输入匹配异常的第一个编码捕获。
编辑从Azodius

纳入评论例如:

try { 
    bufferedReader.read(); 
} catch (FileNotFoundException e) { 
    // FileNotFoundException handled here 
} catch (IOException e) { 
    // Other IOExceptions handled here 
} 

这下面的代码无法编译:

try { 
    bufferedReader.read(); 
} catch (IOException e) { 
    // All IOExceptions (and of course subclasses of IOException) handled here 
} catch (FileNotFoundException e) { 
    // Would never enter this block, because FileNotFoundException is a IOException 
} 

编译消息称:

不可达抓为FileNo块tFoundException。 IOException异常已被catch catch块处理

+0

第一个代码库是一个编译器错误。是不是? – Azodious

+0

@Abodious糟糕 - 是的。这是一个编译器错误。谢谢,我会在答案中注明 – Bohemian

1

第一个适用于这种类型的异常(并且只有那个)。因此,如果您按照您列出的顺序排列上述两种异常类型catch,则会捕获FileNotFoundException

2

只有遇到catch块的异常类型与抛出异常的类型匹配的第一个catch块才会运行(更具体地说,第一个catch块在哪里将运行(e instaceof <exception type>)==true)。其他catch块都不会运行。

例如

try{ 
    BufferedReader.read(); 
} 
catch(FileNotFoundException e){System.out.println("FileNotFoundException");} 
catch(IOException e){System.out.println("IOException");} 

将打印FileNotFoundException如果BufferedReader.read()抛出一个FileNotFoundException

注意以下实际上并不编译:

try{ 
    BufferedReader.read(); 
} 
catch(IOException e){System.out.println("IOException");} 
catch(FileNotFoundException e){System.out.println("FileNotFoundException");} 

因为Java意识到这是不可能的FileNotFoundException被抓,因为所有FileNotFoundException s为也IOException秒。

0

特定异常首先被捕获。如果通用异常被捕获,那么这是一个编译时错误。