DEV Community

Deepikandas
Deepikandas

Posted on

#29 - Exception Handling Throw & Throws Keyword Part3

Throw keyword:
JVM automatically throws system-generated exceptions. All those exceptions are called implicit exceptions.
If we want to throw an exception manually or explicitly, for this, Java provides a keyword throw.

  • In Java exception handling, we use throw keyword to throw a single exception explicitly. It is followed by an instance variable.
  • Using throw keyword, we can throw either checked or unchecked exception in Java.
  • The keyword throw raises an exception by creating a subclass object of Exception explicitly.
  • We mainly use throw keyword to throw custom exception on the basis of some specified condition.
  • We use keyword throw inside the body of method or constructor to invoke an exception.
  • With the help of throw keyword, we cannot throw more than one exception at a time

What is throws in Java?

The throws keyword is used in a method declaration to indicate that the method might not handle an exception itself and instead passes the responsibility to the caller method.

It acts as a warning signal to the programmer:

β€œThis method may generate an exception. Handle it where you call it.”
Why do we use throws?

We use throws because:

Some exceptions cannot or should not be handled immediately
The caller may be better suited to handle the error
It helps in writing clean and modular code
🧠 Syntax of throws
returnType methodName() throws ExceptionType {
// risky code

Difference between Throw and Throws in Java
There are some key difference between throw and throws keyword in Java. They are as:

  • The keyword throw is used to throw an exception explicitly, while the throws clause is used to declare an exception.
  • Throw is followed by an instance variable, while throws is followed by the name of exception class.
  • We use throw keyword inside method body to call an exception, while the throws clause is used in method signature.
  • With throw keyword, we cannot throw more than one exception at a time, while we can declare multiple exceptions with throws.

Top comments (0)