Java throw and throws keyword

On Social Media

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 see custom exceptions later.

The syntax of java throw keyword is given below.

  1. throw exception;  

Let’s see the example of throw IOException.

  1. throw new IOException(“sorry device error);  

In this example, we have created the validate method that takes integer value as a parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise print a message welcome to vote.

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.

Which exception should be declared

Ans) checked exception only, because:

  • unchecked Exception: under your control so correct your code.
  • error: beyond your control e.g. you are unable to do anything if there occurs VirtualMachineError or StackOverflowError.
Watch on YouTube

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. Let’s see the example of java throws clause which describes that checked exceptions can be propagated by throws keyword.

Code

There are two cases:

  1. Case1:You caught the exception i.e. handle the exception using try/catch.

2.Case2:You declare the exception i.e. specifying throws with the method.

Case1: You handle the exception

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

Case2: You declare the exception

  • A)In case you declare the exception, if exception does not occur, the code will be executed fine.
  • B)In case you declare the exception if exception occures, an exception will be thrown at runtime because throws does not handle the exception.

On Social Media

Leave a Reply

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