2016-02-03 70 views
0

是否有可能在抛出异常的方法之外捕获异常?异常句柄

对于例如:

public double[] readFile(String filename) throws IOException 
    { 
    File inFile = new File(filename); 
    Scanner in = new Scanner(inFile); 
    try 
    { 
     readData(in); 
     return data; 
    } 
    finally 
    { 
     in.close(); 
    } 
} 

我怎么会去在main方法捕捉IOException异常? 我可以只做catch(IOException){}吗?

+4

当然,如果该方法没有按” t自己捕获异常,它传播给调用者。 – Berger

+0

或者你可以“捕捉”它,然后重新抛出它(在catch块中),这样调用者就可以获得它。但**从来没有**让你的catch块为空:) – Shark

+0

你如何重新抛出异常?它是一样的只是抛出它,但在捕获? –

回答

1

是土特产品可以做,赶上在someMethod()方法扔这样的例外:

public double[] readFile(String filename) throws IOException 
    { 
    ... 
    } 

在另一种方法例如:

public void someMethod(){ 
    try 
    { 
    readFile(in); 
    return data; 
    }catch(IOException io){ 
    } 
    ... 
    } 
1

你并不需要使用try/catch声明这个方法,因为你不想在里面处理异常,所以你希望它被抛出。 (这是throws关键字做什么)

所以,你可以这样做:

public double[] readFile(String filename) throws IOException 
{ 
    File inFile = new File(filename); 
    Scanner in = new Scanner(inFile); 

    readData(in); 
    // If everything goes normally, the execution flow shall pass on to 
    // the next statements, otherwise if an IOException is thrown, it shall 
    // be handled by the caller method (main) 

    in.close(); 
    return data; 
} 

&您main方法中,处理可能的异常:

try { 
    double[] result = readFile("filename.ext"); 
    // ... 
} 
catch(IOException e) { 
    // Handle the exception 
} 
+1

好多了,那就是我一直在寻找的东西! –