What are the meaning of throw and throws in Java

throw

 

In Java, "throw" and "throws" are keywords used for exception handling.

"throw" is used to explicitly throw an exception within a method. It is followed by the exception object that is being thrown. When an exception is thrown, the normal execution of the method is stopped, and the runtime looks for a matching exception handler to catch the exception and handle it appropriately.

For example, consider the following code: 

 

public void myMethod(int num) {
  if(num < 0) {
    throw new IllegalArgumentException("Number cannot be negative.");
  }
  // rest of the code
}</pre.

In the above code, if the argument "num" is negative, an IllegalArgumentException is thrown using the "throw" keyword.

On the other hand, "throws" is used in the method signature to declare that the method may throw certain types of exceptions. This helps in documenting the possible exceptions that a method can throw and can also help in catching those exceptions at a higher level.

For example, consider the following code: 

 

public void myMethod(int num) throws IOException {
  // method code that may throw an IOException
}

In the above code, the method "myMethod" is declared to potentially throw an IOException using the "throws" keyword.

Submit Your Programming Assignment Details