The other answers have covered why the compiler is unhappy, and what you can do about it. But I think that your real mistake is throwing Exception
in the first place.
Throwing Exception
is almost always a bad idea. The reason is that if your code throws Exception
, it (or someone else's code) then typically has to catch the exception. But the problem with catching Exception
is that your code also catches any / all subtypes of Exception
that might be thrown by your code. That includes unchecked exceptions that might be caused by bugs in your code, etcetera.
For example:
public class Test {
private static Integer a;
private static Integer b;
public static void main(String[] args) {
try {
if (a.equals(b)) {
throw Exception("they are the same");
}
System.out.println("they are different");
} catch (Exception ex) {
System.out.println(ex.message());
}
}
}
When you run this, you will get the mysterious output "null". (Exercise for reader ... figure out precisely why.)
Declaring a method as throws Exception
is even worse, because now the caller is forced to either catch Exception
(bad) or propagate it (worse). Methods that are declared as throws Exception
are like a cancer.
Declaring the main
method as throws Exception
is a special case. The main method is (usually) called by JVM infrastructure that is designed to cope with any exception. It just prints a stacktrace to standard error. Even so, it is probably neater to handle the exceptions yourself. In a "production grade" codebase, you would typically want to log the unexpected exception in the error logs.