• 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>

Our Services:

Java Training | Python Training | Machine Learning with Python Training | Deep Learning with Python Training | Data Science with Python Training | Projects

SILAN Technology, BBSR
Call to: 9439202111  |  9658317757  |  0674-2361252

Comment