java - 方法抛出异常未编译,但 RuntimeException 没有问题

标签 java exception

我编写了以下示例类来试验异常。我有两种相同的方法,一种抛出 RuntimeException,另一种则抛出异常,无法编译。

Sample code

public class Test{

    public static void main(String... args){
        System.out.println(3%-2);
        System.out.println(4%-2);

        Test t1 = new Test();
        t1.mtd1(101);
        t1.mtd2(101);

    }

    public int mtd1( int i) throws RuntimeException{
        System.out.println("mtd");

        return i;
    }

    public int mtd2( int i) throws Exception{
        System.out.println("mtd");

        return i;
    }


}

Error

C:\Java\B-A>javac Test.java
Test.java:10: error: unreported exception Exception; must be caught or declared to be thrown
                t1.mtd2(101);
                       ^
1 error

最佳答案

你有两个选择。您可以在 main() 方法中捕获异常,也可以让 main() 也抛出异常。

选项一:

public static void main(String... args){
    System.out.println(3%-2);
    System.out.println(4%-2);

    Test t1 = new Test();
    try {
        t1.mtd1(101);
        t1.mtd2(101);
    }
    catch (Exception e) {
        // do something
    }
}

选项二:

public static void main(String... args) throws Exception {
    System.out.println(3%-2);
    System.out.println(4%-2);

    Test t1 = new Test();
    t1.mtd1(101);
    t1.mtd2(101);
}

顺便说一句,看到您捕获 RuntimeException 有点奇怪,因为此异常未经检查。通常,未经检查的异常表示在运行时以通常无法处理它们的方式运行的事物。

关于java - 方法抛出异常未编译,但 RuntimeException 没有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36685742/

相关文章:

java - 如何动态指定JMX端口号

java - CVS在文件末尾附加一个,v

java - 为什么HBase使用NavigableMap<Cell, Cell>来存储Cell?

java - Eclipse 中的 jUnit 抛出空指针异常

java - 为什么 java.lang.Exception 不允许在构造函数外设置消息?

java - 调用 Exception.printStackTrace 时出现 AbstractMethodError

java - 使用 CoreNLP 单独标记和后标记

java - 简单日期格式化程序中的月份始终返回 JANUARY

c++ - 从 std::runtime_error 私有(private)继承的类未被捕获为 std::exception

c++ - 初始化列表中的 try/catch 是如何工作的?