java throw keyword

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Java throws exception

Java throws keyword

The Java throw keyword is used to explicitly throw an exception.

We can throw either checked or unchecked exception in java by throws 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);  

Java throw keyword example

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 Arithmetic Exception otherwise print a message welcome to vote.

  1. public class TestThrow1{  
  2.    static void validate(int age){  
  3.      if(age<18)  
  4.       throw new ArithmeticException("not valid");  
  5.      else  
  6.       System.out.println("welcome to vote");  
  7.    }  
  8.    public static void main(String args[]){  
  9.       validate(13);  
  10.       System.out.println("rest of the code...");  
  11.   }  
  12. }  

Test it Now


Exception in thread main java.lang.ArithmeticException:not valid