Monday 24 February 2014

using throw : Specifying the Exceptions Thrown in a Method

throw statement is used to throw an exception inside a method.

Syntax
    throw ExceptionObject;

ExceptionObject is the any subclass of the class Throwable. Since Throwable is the super class for all the exceptions in java.

Example
class Stack{
 int size;
 
 Stack(int size){
  if(size < 0 )
   throw new NegativeArraySizeException("Stack size is less than zero");
  if(size == 0)
   throw new NegativeArraySizeException("Stack size is zero");
  this.size = size;
  System.out.println("Stack created with size " + size);
 }
}
   
class StackTest{
 public static void main(String args[]){
  Stack s1;
  
  try{
   s1 = new Stack(-10);
  }
  catch(Exception e){
   System.out.println(e);
  }
  
  try{
   s1 = new Stack(0);
  }
  catch(Exception e){
   System.out.println(e);
  }
  
  try{
   s1 = new Stack(10);
  }
  catch(Exception e){
   System.out.println(e);
  }
  
 }
}

Output
java.lang.NegativeArraySizeException: Stack size is less than zero
java.lang.NegativeArraySizeException: Stack size is zero
Stack created with size 10

Program, Stack.java has a single parameterized constructor, constructor checks for the size value, before initializing the size variable, if size is less than or equal to zero, then constructor, throw the exceptions with proper messages by using throw clause. StackTest.java tested the various scenarios.

throws clause                                                 throw Vs throws                                                 Home

No comments:

Post a Comment