Javatpoint Logo
Javatpoint Logo

Java throws keyword

The Java throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception. So, it is better for the programmer to provide the exception handling code so that the normal flow of the program can be maintained.

Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked exception such as NullPointerException, it is programmers' fault that he is not checking the code before it being used.

Syntax of Java throws

Which exception should be declared?

Ans: Checked exception only, because:

  • unchecked exception: under our control so we can correct our code.
  • error: beyond our control. For example, we are unable to do anything if there occurs VirtualMachineError or StackOverflowError.

Advantage of Java throws keyword

Now Checked Exception can be propagated (forwarded in call stack).

It provides information to the caller of the method about the exception.

Java throws Example

Let's see the example of Java throws clause which describes that checked exceptions can be propagated by throws keyword.

Testthrows1.java

Test it Now

Output:

exception handled
normal flow...

Rule: If we are calling a method that declares an exception, we must either caught or declare the exception.

There are two cases:

  1. Case 1: We have caught the exception i.e. we have handled the exception using try/catch block.
  2. Case 2: We have declared the exception i.e. specified throws keyword with the method.

Case 1: Handle Exception Using try-catch block

In case we handle the exception, the code will be executed fine whether exception occurs during the program or not.

Testthrows2.java

Test it Now

Output:

exception handled
       normal flow...

Case 2: Declare Exception

  • In case we declare the exception, if exception does not occur, the code will be executed fine.
  • In case we declare the exception and the exception occurs, it will be thrown at runtime because throws does not handle the exception.

Let's see examples for both the scenario.

A) If exception does not occur

Testthrows3.java

Test it Now

Output:

device operation performed
       normal flow...

B) If exception occurs

Testthrows4.java

Test it Now

Output:

Java throw keyword

Difference between throw and throws

Click me for details

Que) Can we rethrow an exception?

Yes, by throwing same exception in catch block.


Next TopicThrow vs Throws





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA