wellnwill Marathahalli Bangalore

throw keyword


  • throw is a keyword used to throw an exception object explicitly either for predefined or user defined exception class if exception object is created by user.
  • throw keyword works like a try block. The difference is try block is automatically find the situation and creates an Exception object implicitly and throw that object. Whereas throw keyword throws predefined or user defined exception class object if exception object is created by user.
  • Throw keyword can throw an object as an exception, only if object is a type of Throwable class.
    Note- All the exception classes provides the following two constructors
  • Default constructor
  • String argument constructor
class Test230
{
public static void main(String[] args)
{
try
{
ArithmeticException ae=new ArithmeticException("we are getting Exception / by zero");
throw ae;
}
catch(ArithmeticException e)
{
 System.out.println("Exception message:"+e);
}
}
}
//O/P- Exception message:" we are getting Exception / by zero.


How to generate user defined Exception

class InvalidAmountException extends Throwable{  
 InvalidAmountException(String s){  
  super(s);  
 }  
} 
class Driver{  
  static void checkAmount(int amount) throws InvalidAmountException{  
     if(amount<100)
	 {
      InvalidAmountException am=new InvalidAmountException("invalid amount"); 
      throw am;	
	 }	  
     else  
      System.out.println("valid amount");  
   }  
 public static void main(String args[])
   {  
      try{  
      checkAmount(10);  
      }
      catch(InvalidAmountException e)
      {
       System.out.println("Exception: "+e);
      }  
System.out.println("Done");  
  }  
}
//O/P-Exception: InvalidDriverException: age is less
        Done.


Footer with Map