Java中未处理的异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27890597/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 05:14:11  来源:igfitidea点击:

Unhandled Exception in Java

javaexceptionunhandled

提问by skulpt

I'm currently in the process of learning how to properly do custom exception and I stumbled upon a problem. Whenever I try to utilize an object of a class that throws this custom exception, my IDE's debugger (I'm using IntelliJ idea) says "Unhandled Exception: InsertExceptionName()". The code, in a simplified manner, looks something like this. In this case, it should return an exception if the randomly generated number is <0.5, and return a number otherwise, but it won't do that. What am I missing?

我目前正在学习如何正确执行自定义异常,但我偶然发现了一个问题。每当我尝试利用抛出此自定义异常的类的对象时,我的 IDE 调试器(我使用的是 IntelliJ 想法)都会显示“未处理的异常:InsertExceptionName()”。代码,以简化的方式,看起来像这样。在这种情况下,如果随机生成的数字 <0.5,它应该返回一个异常,否则返回一个数字,但它不会这样做。我错过了什么?

public class main {
    public static void main(String[] args) {
        double x=Math.random();
        operation op=new operation();
        op.execute(x);
   }
}

-

——

public class operation {
    public operation() {
    }

    public double execute(double x) throws RandomWeirdException {
        if(x<0.5) {
            throw new RandomWeirdException("<0.5");
        }
        return x;
    }
}

-

——

public class RandomWeirdException extends Exception{
    public RandomWeirdException() {
        super();
    }
    public RandomWeirdException(String message) {
        super(message);
    }
}

采纳答案by Mohamad Ali Baydoun

What do you mean "return" an exception? When an exception is thrown, it bubbles up the call stack.

你是什​​么意思“返回”一个异常?当抛出异常时,它会在调用堆栈上冒泡。

You are not handling it in this case. It reaches mainand thus you have an unhandled exception.

在这种情况下,您没有处理它。它到达main,因此您有一个未处理的异常。

If you want to handle an exception, you'd use a try-catchblock. Preferably surrounding mainin this case.

如果你想处理一个异常,你会使用一个try-catch块。main在这种情况下最好环绕。

try {
    // Code that might throw
    // an exception.
} catch (Exception e) {
    // Handle it.
}

Another solution would be to specify that mainthrows a "RandomWeirdException", and not catchit in the first place.

另一种解决方案是指定main抛出“ RandomWeirdException”,而不是catch首先抛出。

public static void main(String[] args) throws RandomWeirdException { ... }

It's preferable to just let functions throw, unless you can reasonably handle the exceptional case. If you just catchfor the sake of catching without doing anything meaningful in an exceptional case, it's the equivalent of hiding an error sometimes.

最好只让 functions throw,除非您可以合理地处理例外情况。如果你只是catch为了捕捉而在特殊情况下没有做任何有意义的事情,那么有时就相当于隐藏了一个错误。

回答by RealSkeptic

You are using the executemethod, without creating a try-catch block for the RandomWiredExceptionwhich it declares that it is throwing. Java required all checked exceptions (that extend Exception) to be properly handled by the caller - either with a try-catch block, or by adding throwsto the calling method (in this case, it is main, though, so it shouldn't have a throwsclause).

您正在使用该execute方法,而没有为RandomWiredException它声明要抛出的对象创建 try-catch 块。Java 要求Exception调用者正确处理所有已检查的异常(即扩展)——要么使用 try-catch 块,要么添加throws到调用方法(在这种情况下,它是main,所以它不应该有throws子句)。

So the proper way to do it is like:

所以正确的做法是这样的:

public class Main {
    public static void main(String[] args) {
        double x=Math.random();
        operation op=new operation();
        try {
            op.execute(x);
        } catch ( RandomWiredException e ) {
            e.printStackTrace();
            System.exit(1);
        }
    }
}

The actual code in the catch clause is up to your application's requirements, of course.

当然,catch 子句中的实际代码取决于您的应用程序的要求。

Note: use uppercase initial letter when you name classes. This is one of the Java styling conventions that will improve your code readability.

注意:命名类时使用大写首字母。这是将提高代码可读性的 Java 样式约定之一。