Back to questions
JuniorTheoryCommon
What happens when this program is compiled and run?
public class Main {
static void fail() { throw new Exception("boom"); }
public static void main(String[] args) {
try {
fail();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}It does not compile
- Expecting
boom: thecatchinmaindoes not coverfail; every method that may throw a checked exception must catch it or declare it withthrows. - Expecting a run-time error: a checked exception is checked by the compiler, so a missing
throwsstops the build, not the running program.
- What changes if
failthrowsnew RuntimeException("boom")instead? - Where do you add
throws Exceptionto make the program printboom?