Online Software Educational Training - IT Tutorials - Online Education Training for Computer Software


Home

JAVA PROGRAMMING

Throw and Throws

The throw Statement 

All Java methods use the throw statement to throw an exception. The throw statement requires a single argument: a throwable object. In the Java system, throwable objects are instances of any subclass of the Throwable class. Here's an example of a throw statement: 

throw someThrowableObject;

The throws Clause

You'll notice that the declaration of the pop method contains this clause: 
throws EmptyStackException

The throws clause specifies that the method can throw an EmptyStackException. As you know, the Java language requires that methods either catch or specify all checked exceptions that can be thrown within the scope of that method. You do this with the throws clause of the method declaration. For more information about this requirement see Java's Catch or Specify Requirement. Also, Specifying the Exceptions Thrown by a Method shows you in more detail how a method can specify the exceptions it can throw.
  

Here is an example using throw and throws statement






Previous

Next