Automation Using Selenium Webdriver
Showing posts with label Difference between throw and throws in java. Show all posts
Showing posts with label Difference between throw and throws in java. Show all posts

Tuesday, 7 February 2017

Difference between throw and throws in java


throw keyword:
  • throw keyword used to throw user defined exceptions.(we can throw predefined exception too)
  • If we are having our own validations in our code we can use this throw keyword.
  • For Ex: BookNotFoundException, InvalidAgeException (user defined).

Program:
  1. package com.instanceofjava;
  2. public class MyExceptionThrow {
  3.  
  4.  public static void main(String a[]){
  5.  
  6.  try{
  7.  
  8. MyExceptionThrow thr = new MyExceptionThrow();
  9. System.out.println("length of INDU is "+thr.getStringSize("INDU"));
  10. System.out.println("length of SAIDESH is "+thr.getStringSize("SAIDSH"));
  11. System.out.println("length of null string is "+thr.getStringSize(null)); 
  12.  
  13.  }
  14. catch (Exception ex){
  15.   System.out.println("Exception message: "+ex.getMessage());  
  16.  }
  17.  }
  18.  
  19.  public int getStringSize(String str) throws Exception{
  20.  
  21.  if(str == null){
  22.    throw new Exception("String input is null");  
  23.  }
  24.  return str.length();
  25. }
  26.  
  27. }


Output
length of INDU is 4
length of SAIDESH is 5
Exception message: String input is null

throws keyword:

  •  The functionality of throws keyword is only to explicitly to mention that the method is proven transfer un handled exceptions to the calling place.

Program:
  1. package com.instanceofjava;
  2. public class ExcpetionDemo {
  3.  
  4. public static void main(String agrs[]){
  5.  
  6. try
  7. {
  8. //statements
  9. }
  10. catch(Exception e)
  11. {
  12. System.out.println(e);
  13. }
  14. finally(){compulsorily executable statements
  15. }
  16. }
  17.  
  18. }