Java Design Pattern
Introduction to Java 10
Introduction to Java 11
Introduction to Java 12

Java throw keyword

  • • When we want to throw an exception explicitly, then we should use throw keyword.
  • • We can throw either checked or unchecked exception in java by throw keyword. The throw keyword is mainly used to throw customized exception(exception defined by the user).
  • • The general form to declare throw an exception is : throw new exception class name;
  • • For example, throw new NullPointerException("Demo");

Let's see an example;

Example
class ThrowDemo
{ 
	static void validate(int income)
	{
		if(income<30000)
		throw new ArithmeticException("not able to get loan"); 
		else
		System.out.println("eligible for getting loan");
	}
	public static void main(String args[])
	{
		validate(18000);  
	}
}

Output

Exception in thread "main" java.lang.ArithmeticException: not able to get loan
at ThrowDemo.validate<ThrowDemo.java:6>
at ThrowDemo.main<ThrowDemo.java:12>

About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.


We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc






 PreviousNext