throw keyword in java

In java throw keyword is used to implement custom exception. With the help of throw keyword one can easily throw checked as well as unchecked exception.

The main advantage is throw keyword in java is to explicitly throw an exception.

Syntax of throw keyword

throw exception;

Example:

throw new IOException(“Link fail”); 

Program to show use of throw keyword using exception handling

class ThrowDemo { static void checkAge(int age) { if(age<18) throw new ArithmeticException("Invalid Age"); else System.out.println("You are eligible to vote"); } public static void main(String args[]) { checkAge(10); System.out.println("rest of the code..."); }
}

Output: