«Back to Home

Core Java

Topics

Throw Exception In Java

Throw Exception
 
In Java, throw keyword is used to throw an exception explicitly.
 
In Java, we can throw checked or unchecked exceptions by throw keyword. The throw keyword is used to throw user defined or custom exception.
 
Syntax

throw exception;
 
Let’s see an example, given below.
 
Code
  1. package exceptionHandling;  
  2. public class ThrowExample {  
  3.     static void childAge(int age) {  
  4.         if (age > 12) {  
  5.             throw new ArithmeticException("Not allowed");  
  6.         } else {  
  7.             System.out.println("Welcome to Games zone");  
  8.         }  
  9.     }  
  10.     public static void main(String args[]) {  
  11.         childAge(15);  
  12.         System.out.println("Children likes games");  
  13.     }  
  14. }  
20

Output

21

In the example, shown above, the childAge method takes an integer value as a parameter. If the age is greater than 12, it throws the exception otherwise print a message welcome to games zone and children likes games.
 
Summary

Thus, we learnt throw keyword is used to throw an exception explicitly in Java and also learnt how we can throw the exception.