Google News
logo
Java Throw
Throw
1) The main purpose of the throw keyword is to creation of Exception object explicitly either for predefined or user defined .
2) Throw keyword works like a try block. The difference is try block is automatically find the situation and creates a Exception object implicitly. Whereas throw keyword creates a Exception object explicitly.
Throw program
import java.util.*; 
class Test 
{ 
static void validate(int age) 
{ 
if (age<18) 
{ 
throw new ArithmeticException("not elgible for vote"); 
} 
else 
{ 
System.out.println("welcome to the voteing"); 
} 
}
public static void main(String[] args) 
{ 
Scanner s=new Scanner(System.in); 
System.out.println("please enter your age "); 
int n=s.nextInt(); 
validate(n); 
} 
}
Output :
output: please enter your age 12 Exception in thread "main" java.lang.ArithmeticException: not elgible for vote at ee.Test.validate(Test.java:10) at ee.Test.main(Test.java:22) please enter your age 20 welcome to the voteing