throw vs. throws

In Java, throw and throws are both related to exceptions but serve different purposes:

throw

  • The throw keyword is used to explicitly throw an exception in a method or block of code.
  • It is followed by an instance of an exception (e.g., new Exception()).
  • We can use throw inside a method to indicate that something went wrong, and we want to signal that error to the caller.

Example

throws

  • The throws keyword is used in a method signature to declare that a method can throw one or more exceptions. It tells the compiler and the caller that this method might throw a particular exception, and it needs to be handled.
  • throws does not throw the exception itself, it just signals that the method could potentially throw it.

Example

throw vs throws

Feature throw throws
Purpose Used to explicitly throw an exception. Used to declare exceptions a method can throw.
Syntax throw new Exception("Message"); public void method() throws Exception {}
Where Used Inside a method or block of code. In the method signature.
Function Actually throws the exception. Tells the compiler that an exception may be thrown, but doesn’t throw it itself.
Control Directly controls when an exception is thrown. Indicates that the method might throw an exception.
Example throw new IllegalArgumentException("Invalid input"); public void readFile() throws IOException {}