Throw and Throws

Throw and Throws

In Java, throw and throws are keywords used in exception handling to either throw an exception explicitly or declare that a method may throw an exception, respectively.

The throw statement is used to explicitly throw an exception from a method or block of code. It is used when a certain condition arises that cannot be handled by the program and the programmer wants to terminate the program or display an error message. The general syntax for throw is:

throw new ExceptionClassName(“Error message”);

Here, ExceptionClassName is the name of the exception that is to be thrown and “Error message” is the message to be displayed when the exception is thrown.

The throws keyword, on the other hand, is used to declare that a method may throw a certain type of exception. It is used in the method signature to indicate that the method can throw an exception and any code that calls the method should handle the exception appropriately. The general syntax for throws is:

accessSpecifier returnType methodName(parameters) throws ExceptionClassName1, ExceptionClassName2, … {

    // code

} Here, accessSpecifier is the access modifier for the method, returnType is the type of value returned by the method, methodName is the name of the method, parameters are the arguments passed to the method, and ExceptionClassName1, ExceptionClassName2, … are the names of the exceptions that the method may throw. If a method uses throws to declare that it may throw an exception, it is the responsibility of the caller to handle the exception.

Apply for Core Java Developer Certification Now!!

https://www.vskills.in/certification/certified-core-java-developer

Back to Tutorial

Share this post
[social_warfare]
Try—Catch—Finally Blocks
Input-Output

Get industry recognized certification – Contact us

keyboard_arrow_up