Throw and Throws

  • Eclipse: Oxygen
  • Java: 1.8

Throw and Throws

Throws are used to suppress the error if the user doesn’t want to specify the try and catch block. Note that this doesn’t handle the error only suppresses it. It should be used only when the developer is sure that the error doesn’t occur.

The throw is used to forcefully throw an error where it is decided by the developer regarding the certain conditions.

Output

Message from someMethod

catch block of the main method

The keyword “throw” is used to throw an exception from any method or static block, while the keyword “throws”, used in a method declaration, indicates what exception can be thrown with this method. They are not interchangeable.

In a program, if there is a possibility that an exception occurs, the compiler always warns us and we must handle that checked exception. Otherwise, we will get a compile-time error.

To avoid this compile-time error, we can handle the exception in two ways:

  1. By using try catch block
  2. By using throws keyword

Output

message from catch block

Message from someMethod

We can use the keyword throws to delegate the responsibility of handling exceptions to the caller, then the caller method is responsible for handling that exception.

Output

Runtime error

Contributed by Poonam Tomar


Full stack Java Developer

   Buy me a coffee!

 

PayTM QR (INDIA)

Download file

Leave a Reply

avatar
  Subscribe  
Notify of
Close Menu