Throw & Throws in Java | Exception Handling – Part 3

In this java programming tutorial post, we will study and understand the working of throw and throws keyword which helps in performing exception handling in java. Before we start of with this topic, you can checkout the Part 1 of Exception handling where we discussed the overall concept of Exception handling and how it works in Java. Click here to go the article.

Java Exception Handling Keywords –

There are 5 keywords used in java exception handling.

  • try (click here to check this article)
  • catch (click here to check this article)
  • finally (click here to check this article)
  • throw 
  • throws 
Java Exception propagation

An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous method,If not caught there, the exception again drops down to the previous method, and so on until they are caught or until they reach the very bottom of the call stack.This is called exception propagation.

Output –

exception propagation in java programming

Java throw keyword

The Java throw keyword is used to explicitly throw an exception. We can throw either checked or uncheked exception in java by throw keyword. The throw keyword is mainly used to throw custom exception(we will study about them in further tutorials)

The syntax of java throw keyword is given below.

Let’s see the example of throw IOException.
Java Throw Keyword Program example –
Output –
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 normal flow 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 performing check up before the code being used.

Primary advantage of throws keyword is it provides information to the caller of the method about the exception.

Syntax of java throws
Java throws example

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

Output –

Difference between throw and throws in Java

There are many differences between throw and throws keywords. A list of differences between throw and throws are given below:

No.throwthrows
1)Java throw keyword is used to explicitly throw an exception.Java throws keyword is used to declare an exception.
2)Throw is followed by an instance.Throws is followed by class.
3)Throw is used within the method.Throws is used with the method signature.
4)You cannot throw multiple exceptions.You can declare multiple exceptions e.g.
public void method()throws IOException,SQLException.

 

Leave a Reply

Your email address will not be published. Required fields are marked *