Unhandled Exception in Java

↘锁芯ラ 提交于 2019-11-27 02:12:03

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 main and thus you have an unhandled exception.

If you want to handle an exception, you'd use a try-catch block. Preferably surrounding main in this case.

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

Another solution would be to specify that main throws a "RandomWeirdException", and not catch it in the first place.

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 catch for the sake of catching without doing anything meaningful in an exceptional case, it's the equivalent of hiding an error sometimes.

You are using the execute method, without creating a try-catch block for the RandomWiredException which 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 throws to the calling method (in this case, it is main, though, so it shouldn't have a throws clause).

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!