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);
}
}
You are using the
execute
method, without creating a try-catch block for theRandomWiredException
which it declares that it is throwing. Java required all checked exceptions (that extendException
) to be properly handled by the caller - either with a try-catch block, or by addingthrows
to the calling method (in this case, it ismain
, though, so it shouldn't have athrows
clause).So the proper way to do it is like:
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.
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 surroundingmain
in this case.Another solution would be to specify that
main
throws a "RandomWeirdException
", and notcatch
it in the first place.It's preferable to just let functions
throw
, unless you can reasonably handle the exceptional case. If you justcatch
for the sake of catching without doing anything meaningful in an exceptional case, it's the equivalent of hiding an error sometimes.