Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

Unhandled Exception in Java

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?

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);
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...