Difference between throw and throws keyword?

Difference between throw and throws keyword?

Difference between throw and throws keyword?

Difference between throw and throws keyword?

throw keyword

  • Sometimes we can create exception object explicitly we can handover to the JVM manually. For this, we have to use Throw keyword.
    • Example:- throws new AirthmeticException(“/by zero”);
  • Hence the main objective of Throw keyword is to handover our created exception object to JVM manually.
  • Hence the result of following two programs is exactly same.
  • public class Test{

    public static void main(String args[])

    {

    System.out.println(10/0);

    }

    }

    public class Test{

    public static void main(String args[])

    {

    throw new ArithmeticException(“/ by zero explicitly”);

    }

    }

    Exception in thread “main” java.lang.ArithmeticException: / by zero Exception in thread “main” java.lang.ArithmeticException: / by zero explicitly
    In this case, the main method is responsible to create an exception object and Hanover to JVM In this case programmer is creating exception object explicitly and handover to JVM manually
  • After throw statement we are not allowed to write any statement directly otherwise we will get compile time error saying unreachable statement. 
  • We can use throw keyword only for throwable types. If we are trying to use for normal java object we will get compile time error saying incompatible types. 

Throws keyword

  • In our program if there is a possibility of raising checked exception then compulsory we should handle that checked exception otherwise we will get compile time error saying unreported Exception ABC: must be declared to be thrown.
  • We can handle this compile time error by using the following two ways
    1. By using try-catch
    2. By using throws keyword
  • We can use throws keyword to delegate the responsibility of exception handling to the caller(it may be another method or JVM) then caller method is responsible to handle that exception.
  • It is required only for checked exception
  • Uses of throws keyword for unchecked exception there is no impact.
  • It is required only to convince compiler and uses of throws doesn’t prevent abnormal termination of the program.
  • It is recommended to use try-catch over throws keywords.
  • We can use throws keyword for method and constructors but not for classes.
  • We can use throws keyword only for Throwable types. If you are trying to use for normal java classes then we will get compile time error saying incompatible types. 
  • Within the try block if there is no chance of raising an exception then we can’t write catch block for that exception otherwise we will get compile time error saying ” exception xxx is never thrown in body of corresponding try statement”. But this rule is applicable only for fully checked exceptions.

Leave a Reply

Your email address will not be published. Required fields are marked *

*