未处理的异常:java.io.IOException

时间:2018-05-07 02:28:50

标签: java exception io ioexception

我的代码块在这里。它告诉我IOException未处理。

import UIKit

func bisection(x: Double) -> Double {

let constant1 = Double((1+2*60))
let constant2 = Double(1+4*60)

let m = (constant1 - pow(constant2, 0.5)) / (2.0*60.0)
return m
}

let bis = bisection(x: 1.0)
print(bis)

我认为我能做的一种方式就是这样:

public static void main(String[] args) {
        FileWriter locFile = null;              
        try{                                  
            locFile = new FileWriter("locFile.txt");
            for(Location location : locations.values()){
                locFile.write(location.getLocationID()+", "+location.getDescription()+"\n");
            }
        }catch(IOException e){                     
            throw new IOException("My message");
            e.printStackTrace();
        }finally{
            try{
                if(locFile != null){
                    System.out.println("Attempting to close locFile");
                    locFile.close();
                }
            }catch(IOException e){
                e.printStackTrace();
            }
        }
    }

但是我可以在catch块中抛出异常吗?这样做是否实际或普遍?

1 个答案:

答案 0 :(得分:0)

如果您将以下来电移至throw,则代码runs fine for me

throw new IOException("My message");

如果您确实想要重新提出IOException,那么您需要将main()方法标记为抛出异常,例如

public static void main(String[] args) throws IOException

在某些情况下,您可能希望执行此类操作。但更典型的是,我所看到/做的是,如果一个方法抛出异常,你可能不会在该方法中捕获任何东西。

相关问题