如何捕获函数抛出的异常?

时间:2014-09-24 21:47:37

标签: java ioexception

我的函数抛出了以下格式的IOException。我如何捕获这样写的异常,我使用了标准的try / catch块。

public static void loader(int[] arr, String file) throws IOException
{
    Scanner sc = new Scanner(file);
    for(int i = 0; sc.hasNextInt(16) ; ++i)
        arr[i] = sc.nextInt(16);
}

5 个答案:

答案 0 :(得分:1)

当您在方法的签名中声明选中Exception时,您不需要在此方法中处理它。相反,任何调用loader的方法都要在其标头中声明此Exception或在try / catch块中处理它:

public void someMethod() throws IOException {
   loader(...);
}

// or

public void someMethod() {
   try {
     loader(...);
   } catch (IOException io) {
      //...
   }
}

答案 1 :(得分:0)

try{
//method call
}
catch (IOException e) {
//handle Exception
}

或者,如果声明方法的类实现了AutoClosable interface

,则使用try with resources

答案 2 :(得分:0)

使用try / catch方法填充代码:

像这样:

public static void loader(int[] arr, String file) throws IOException
{

try{
    Scanner sc = new Scanner(file);
    for(int i = 0; sc.hasNextInt(16) ; ++i)
    arr[i] = sc.nextInt(16);
}catch(IOException e) {
//Do whatever you want with the exception
}

}

答案 3 :(得分:0)

您的方法实际上只是将IOException发送到调用堆栈上的下一个方法。在这种情况下,您的调用代码需要处理异常:

public void foo() {
    // assuming your method is in the Bar class
    int[] secretCodes = {};
    try {
        Bar.loader(secretCodes, new File("C:\\tmp.txt");
    } catch(IOException ex) {
        ex.printStackTrace();
    }
}

但是,要使用try / catch块,您应该从方法签名中删除IOException。然后,您将不再需要调用您的方法的代码包含try / catch块。

在这种情况下,您的代码将如下所示:

public static void loader(int[] arr, String file)
{
    try {
        Scanner sc = new Scanner(file);
        for(int i = 0; sc.hasNextInt(16) ; ++i)
            arr[i] = sc.nextInt(16);
    } catch(IOException ex) {
        ex.printStackTrace(); // Or however you want to handle the exception
    }
}

请注意,您不再需要方法签名中的throws IOException,因为它已在方法中处理过。 (当然,除非你的方法在try块之外抛出一个。)

答案 4 :(得分:0)

您有两种选择:

  1. 处理调用代码中的异常:

    try {
        YourClass.loader(/*...relevant args...*/);
    }
    catch (IOException ioe) {
        // ...do something with `ioe`...
    }
    

  2. 处理里面的方法:

    public static void loader(int[] arr, String file)
    {
        try {
            Scanner sc = new Scanner(file);
            for(int i = 0; sc.hasNextInt(16) ; ++i)
                arr[i] = sc.nextInt(16);
        }
        catch (IO Exception ioe) {
            /*...do something with `ioe`....*/
        }
    }
    
  3. 您选择的是由您自己决定的。在外层处理异常通常很有用(#1),但这完全取决于代码和上下文。