Unreported exception java.io.IOException when compiling Java code

心已入冬 提交于 2019-12-04 06:22:14

问题


I am experiencing a problem with this code:

public class gravityv1 {
    public static double[] calculategravity(double[] mass, int[] diameter) {
        double[] gravity = new double[mass.length];

        for (int n = 0; n < mass.length; n++) {
            gravity[n] = (6.67E-11 * mass[n]) / Math.pow((diameter[n] / 2), 2);

        }

        return gravity;
    }

    public static void print(double[] gravity, double[] mass, int[] diameter, String[] planet) {
        System.out.println("                          Planetary Data");
        System.out.println("Planet          Diameter(km)          Mass(kg)          g(m/s^2)");
        System.out.println("---------------------------------------------------------------------");
        for (int n = 0; n < planet.length; n++)
        System.out.printf("%-7s%15d%20.3f%14.2f", planet[n], diameter[n], mass[n], gravity[n]);
    }

    public static void printFile(double[] gravity) throws IOException {
        PrintWriter outFile = new PrintWriter(new File("gravity.txt"));
        for (double gravita: gravity) {
            outFile.println(gravita);
        }
        outFile.close();
    }

    public static void main(String[] args) {
        String[] planet = {
            "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"
        };
        double[] mass = {.330E24, 4.87E24, 5.97E24, 0.642E24, 1898E24, 568E24, 86.8E24, 102E24
        };
        int[] diameter = {
            4879, 12104, 12756, 6792, 142984, 120536, 51118, 49528
        };

        double[] gravity = calculategravity(mass, diameter);

        print(gravity, mass, diameter, planet);
        printFile(gravity);
    }
}

Whenever I try to compile this code, an error appears at "printFile(gravity)", which is located at the bottom. The error message is:

unreported exception java.io.IOException; must be caught or declared to be thrown.

I don't know what to do.


回答1:


You need a try-catch block in your main method around all methods that throw an IOException:

try {
    printFile(gravity);
} catch (IOException ex) {
    // handle exception here
}

Include all methods that have throws IOException after the signature.




回答2:


Change your main method declaration to:

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

In Java, each method A calling another method B, must declare all the exceptions
which B can throw (unless they are descendants of RuntimeException or unless A
is catching and processing them explicitly in a try-catch block).

In your case A is main, B is printFile.



来源:https://stackoverflow.com/questions/27115517/unreported-exception-java-io-ioexception-when-compiling-java-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!