Java:Using throw
When to use throw in a Java method declaration?
All methods use the throw statement to throw an exception. The throw statement requires a single argument: a Throwable object. Throwable object are instances of any subclass of the Throwable classThe flow of execution stops immediately after the throw statement;any subsequent statements are not executed.
The general form is as shown below:
throw ThrowableInstance;
throw ThrowableInstance;
Here,ThrowableInstance must be an object of type Throwable or a subclass of Throwable.
Example:
{
static void validate(int age)
{
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[])
{
validate(13);
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException: not valid
No comments :
Post a Comment