throw null, and the static type of a throw
The compiler made main handle Exception, but at run time the more specific catch matched the real object.
throw is a statement that throws one exception object right now. throws is part of a method signature that warns callers which checked exceptions the method may pass up to them.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write static double sqrtChecked(double x) that throws IllegalArgumentException with the value in the message for negative input. Call it with 9 and -4, catching and printing the message.
Write a class Door with open(), close() and lock(), where open() on a locked door and lock() on an open door throw IllegalStateException. Run a sequence that ends in an error and print each step.
Write static char grade(int marks) using a switch expression over marks / 10 that returns 'A' for 9 and 10, 'B' for 8, 'C' for 6 and 7, 'F' for 0..5, and throws for anything else. Test with 95, 72, 40 and 130.
Explain it without notes
What is the difference between throw and throws?
What is a guard clause, and which standard exceptions would you use in one?
Does throwing new IllegalStateException() through a variable of type Exception need a throws clause? Why?
Why does a method that ends with a call to an always-throwing helper fail to compile, and how do you fix it?
Expected output
throw null gives: NullPointerException
message: Cannot throw exception because "Main.missing" is null
caught as IllegalStateException: really a runtime exception