首页 > 解决方案 > 在 Eclipse 中提示“未处理的异常类型 xxx”

问题描述

我不认为我真的理解 try-catch 块和 throws 。

public class TestException {

    public static void main(String[] args) {
        new TestException().tt();
    }

    public void tt() {
        try {
            throw new RuntimeException();
        }catch (Exception e) {
            throw e;
        }
    }
}

在 Eclipse 中,有一个关于“未处理的异常类型 xxx”的错误提示,如果你运行它,你会得到一个 Exception in thread "main" java.lang.Error: Unresolved compilation problem: Unhandled exception type Exception 但是在 Idea 中,没有错误。它运行并正确抛出异常。

在我看来,'e' 没有被声明为 RuntimeException(尽管它是一个 RuntimeException),所以 tt() 方法必须用 throws 声明。但实际上并非如此。为什么?

标签: javaexception

解决方案


这应该回答你的问题:

public class TestException {

    public static void main(String[] args) {
        new TestException().tt();
    }

    public void tt() {
        try {
            throw new RuntimeException();
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

如果你使用throws,你会告诉那些使用你的函数的人,“我的函数可能会抛出异常。你必须处理它。”

你应该在这句话中得到throwsthrows的区别。

如果您使用 try-catch,您将处理该异常。

1)您应该添加throws关键字,如下所示

public class TestException {
    public static void main(String[] args) {
        new TestException().tt();
    }

    public void tt() **throws Exception** {
        try {
            throw new RuntimeException();
        }catch (Exception e) {
            throw e;
        }
    }

}

2) 处理使用函数的异常

public class TestException {
    public static void main(String[] args) {
        try{
            new TestException().tt();
        }catch(Exception e){
            System.out.println("Error handled");
        }
    }
    public void tt() throws Exception {
        try {
            throw new RuntimeException();
        }catch (Exception e) {
            throw e;
        }
    }
}

一般来说,如果你捕捉到一个异常,你就会处理它。像这样

public class TestException {
    public static void main(String[] args) {
        new TestException().tt();
    }

    public void tt() {
        try {
            throw new RuntimeException();
        }catch (Exception e) {
            System.out.println("Error caught! ")
        }
    }
}

或者

public class TestException {
    public static void main(String[] args) {
        try  {
          new TestException().tt();
        }catch(Exception e){
          System.out.println("Error caught! ")
        }
    }

    public void tt() throws RuntimeException {
        throw new RuntimeException();
    }
}

你也可以抛出其他的异常

public class TestException {

    public static void main(String[] args) {
        try{
            new TestException().a();
        }catch(Exception e){
            System.out.println("Error handled");
        }
    }

    public void a() throws Exception {
        b();
    }

    public void b() throws Exception {
        c();
    }

    public void c() throws Exception {
        throw new RuntimeException();
    }
}

推荐阅读