编译Java代码时未报告的异常java.io.IOException [英] Unreported exception java.io.IOException when compiling Java code

查看:150
本文介绍了编译Java代码时未报告的异常java.io.IOException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到此代码的问题:

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);
    }
}

每当我尝试编译此代码时,都会出现错误在 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:


未报告的异常java.io.IOException;必须被抓住或宣布
被抛出。

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

我不知道该怎么办。

推荐答案

将主要方法声明更改为:

Change your main method declaration to:

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

在Java中,每个方法A调用另一个方法B,必须声明所有异常
(除非它们是 RuntimeException 的后代,或者除非A $
正在捕获并在try-catch中显式处理它们块)。

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).

在你的情况下,A是 main ,B是 printFile

In your case A is main, B is printFile.

这篇关于编译Java代码时未报告的异常java.io.IOException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆