Throw keyword in java with Example

It is used to create a new Exception object and throw it. Using throw keyword you can declare only one Exception at a time.

It is mainly used to throw custom exceptions.

One can also say Throw keyword is used to transfer control from try block to catch block.

Syntax :

throw new IOException("cannot open new connection");  

Example : To show throw Exception usage

    
public class TestThrowInException {

  static void validate(Integer salary) {
    
    int gross;
    if (salary == null)
      throw new NullPointerException("not valid");
    else {
      gross = salary + 1000;
    }
    System.out.println("gross salary is :" + gross);
  }

  public static void main(String[] args) {

    try {
      validate(null);
    } catch (Exception e) {
      System.out.println(e);
    }
  }

}

OUTPUT

java.lang.NullPointerException: not valid

Summary

So here we are, we hope now you are confident and know how to use throw keyword in Exceptions in java.

We tried our best to simplify the explanation, if you feel any difference or you need help in understanding any such thing, then feel free to contact us through email and subscribe to ProgrammerToday.