๐ŸŽ‰ Special Offer !    Code: GET300OFF    Flat โ‚น300 OFF on every Java Course
Grab Deal ๐Ÿš€

"throw" vs "throws" in Java  


throw vs throws

  • throw
    • The throw keyword is used to actually throw an exception object from a method or block of code.
    • It can throw only one exception object at a time.
    • Mostly used for unchecked exceptions but can also throw checked exceptions (requires handling).
    • Syntax example :-
      • throw new IOException("File not found");
  • throws
    • The throws keyword is used in a method declaration to declare the exceptions that a method might throw.
    • We can declare one or multiple exceptions, separated by commas.
    • Mainly used for checked exceptions, but can also declare unchecked exceptions (not necessary).
    • Syntax example :-
      • void readFile() throws IOException, SQLException { }
Below are some differences between throw and throws:
Aspect throw throws
Definition Used to actually throw an exception object from a method or block of code. Used in method declaration to declare the exceptions that a method might throw.
Usage Location Inside a method or a block of code. In method or constructor declaration only.
Number of Exceptions Can throw only one exception object at a time. Can declare multiple exceptions separated by commas.
Checked / Unchecked Can throw both checked and unchecked exceptions. Mainly for checked exceptions; can declare unchecked exceptions but not necessary.
Effect on Caller Immediately transfers the exception to the caller. Informs the caller that it should handle the declared exceptions.
Example throw new IOException("File not found"); void readFile() throws IOException, SQLException { }
Requirement Checked exceptions must be handled using try-catch or declared with throws. Caller must handle checked exceptions declared with throws.