☕ Java Beginner

What is the difference between throw and throws in Java?

Answer

throw is a statement used inside a method body to explicitly throw an exception object: throw new IllegalArgumentException("Value must be positive");. It transfers control to the nearest matching catch block or propagates up the call stack. throws is a declaration in the method signature that declares what checked exceptions the method might throw, warning callers that they need to handle them: public void readFile() throws IOException. A method can declare multiple exceptions with throws. Think of it this way: throw is the action of throwing, throws is the warning on the label.