Java throw Keyword
throw
Throw keyword is used for manually (explicitly) throwing an exception.
Since throw is used for manually throwing an exception it is used within the method.
It doesn't allows us to throw multiple exceptions at a time. We have to go for the throws keyword.
Syntax
throw ThrowableInstance
or
throw new ExceptionType ("String");
Important points
- Throwable instance must be an object of type Throwable or subclass of Throwable.
- Primitive types such as int , char,String and object are non throwable classes cannot be used as Exceptions.
- We can obtain a Throwable object using either parameter in catch clause or by creating new operator (Unknown object).
- We should avoid further statements after throw keyword because code becomes unreachable from that throw statement.
Example
try
{
throw new NullPointerException ("Null Exception");
}
catch(NullPointerException e)
{
System.out.println("Null pointer exception caught");
}