Java Throw Exception

The throw keyword in Java is used to “throw” an exception.

By using Java throw keyword, we can throw either checked nor unchecked exceptions. The throw keyword is mainly used to throw custom exception.

Syntax of the Java throw keyword is written below :

throw exception;  

and here’s an ArithmeticException:

throw new ArithmeticException("not valid");

Example :

public class ThrowExmpl{  
   static void validate(int age){  
     if(age<18)  
      throw new ArithmeticException("not valid");  
     else  
      System.out.println("You can vote");  
   }  
   public static void main(String args[]){  
      validate(13);  
      System.out.println("Throw Example");  
  }  
} 

This code will throw an exeption, and why is that?

It’s because the value of the “age” is smaller than 18, and so it will throw us an ArithmeticExeption and print “not valid”, like this :

Exception in thread "main" java.lang.ArithmeticException: not valid
	at ThrowExmpl.validate(ThrowExmpl.java:4)
	at ThrowExmpl.main(ThrowExmpl.java:9)

But if we change the value of the age to = 18 or more than 18

public class ThrowExmpl{  
   static void validate(int age){  
     if(age<18)  
      throw new ArithmeticException("not valid");  
     else  
      System.out.println("You can vote");  
   }  
   public static void main(String args[]){  
      validate(18);  
      System.out.println("Throw Example");  
  }  
} 

the code won’t throw any exception and instead, it will run and print out the “you will vote” string.

You can vote
Throw Example

Published by

Rafif Santika

The programming language that I specialize in is Java, because I think Java programming language is more universal and of course because I like it regardless of any reason.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.