You can throw exceptions yourself using the throw keyword followed by a new exception object:
public static int divide(int a, int b) {
if (b == 0) {
throw new IllegalArgumentException("Divisor cannot be zero");
}
return a / b;
}
The throw statement immediately exits the method. No code after it in the same block will run. The exception propagates up to the caller, just like exceptions thrown by Java itself.
Notice the difference: throw is a statement that creates and throws one exception. throws is a keyword in a method signature that declares what checked exceptions the method might throw. Mixing them up is a common mistake.