Java 方法引发异常未编译,但RuntimeException没有问题

Java 方法引发异常未编译,但RuntimeException没有问题,java,exception,Java,Exception,我编写了下面的示例类来尝试异常。我有两个相同的方法,一个抛出RuntimeException,而另一个没有编译异常 示例代码 错误 你有两个选择。您可以在main()方法中捕获异常,也可以让main()也抛出异常 选项一: public static void main(String... args){ System.out.println(3%-2); System.out.println(4%-2); Test t1 = new Test(); try {

我编写了下面的示例类来尝试异常。我有两个相同的方法,一个抛出RuntimeException,而另一个没有编译异常

示例代码

错误


你有两个选择。您可以在
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);
}
选项二:

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
有点奇怪,因为此异常未被选中。通常未检查的异常表示在运行时以通常不可能处理的方式运行的事物。

您有两种选择。您可以在
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);
}
选项二:

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
有点奇怪,因为此异常未被选中。通常未检查的异常表示在运行时运行的事物,通常不可能处理它们。

从类RuntimeException派生的所有异常都称为未检查的异常。所有其他异常都是检查异常。必须在代码中的某个位置捕获选中的异常。如果不是,代码将不会编译。

从类RuntimeException派生的所有异常都称为未检查的异常。所有其他异常都是检查异常。必须在代码中的某个位置捕获选中的异常。如果没有,代码将不会编译。

当方法声明有一个或多个使用throws子句定义的异常时,方法调用必须处理所有已定义的异常。因此,请使用try catch来处理。当方法声明有一个或多个使用throws子句定义的异常时,方法调用必须处理所有已定义的异常。因此,请使用试着抓住。