throw keyword

throw

  • Used to throw an exception explicitly and catch it
  • Syntax
    throw ThrowableInstance;
  • ThrowableInstance must be an object of type Throwable or a subclass of Throwable.
  • Primitive types, such as int or char, as well as non-Throwable classes, such as String & Object, cannot be used as exceptions.
  • The nearest enclosing try block is inspected to see if it has a catch statement that matches the type of exception. If it does find a match, control is transferred to that statement. If not, then the next enclosing try statement is inspected, and so on.
  • If no matching catch is found, then the default exception handler halts the program & prints the stack trace.
Example
class sample
{
static void demo()
{
try
{
System.out.println(“Inside demo”);
throw new NullPointerException(“Exceprion data”);
}
catch(NullPointerException ne)
{
System.out.println(ne);
}
}
}
class test
{
public static void main(String args[])
{
sample.demo();
}
}

Output:
Inside demo
java.lang.NullPointerException: Exceprion data

Leave a Reply

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