Saturday, 23 May 2015

Difference between throw and throws

throw and throws in Java are two keywords used for exception handling. These two keywords are, functionality wise, very different though.

  • throw is used to throw an exception.
  • throws is used to declare an exception, in the method signature, that can be thrown from a method.

Difference between throw and throws

  1. We can declare multiple exceptions as a comma separated list with throws statement. We can throw only one exception using throw keyword.

    throws Example

    public void displayFile() throws IOException, , ArithmeticException

    throw Example

    throw new NullPointerException();
    throw new FileNotFoundException();
  2. Where throw is followed by an object of the Exception class, throws is followed by exception class names themselves.

    throw Example

    catch(FileNotFoundException fExp){   
     // throwing fExp which is an object of FileNotFoundException type
     throw fExp;
    // creating object and throwing
    throw new FileNotFoundException();

    throws Example

    public void displayFile() throws IOException, ArithmeticException

    It can be seen that Exception class name itself is in the declaration.

  3. throws clause in used to declare an exception in the signature of the method where as throw keyword is used to throw an exception explicitly with in the code of the method or from a static block.

    throw from a static block

    static int i;
    static int b;
    static {
     System.out.println("in static block");
      i = 5;
      b = i * 5;
     }catch(Exception exp){
      System.out.println("Exception while initializing" + exp.getMessage());
      throw exp;
     //System.out.println("Values " + i + " " +  b);

  4. throws clause is used to declare that the method may throw the declared exceptions and calling method should provide the exception handling code where as throw actually throws the exception and the run time system goes through the method hierarchy to search for a method that can handle the exception.

That's all for this topic Difference between throw and throws. If you have any doubt or any suggestions to make please drop a comment. Thanks!

Related Topics

  1. throws clause
  2. throw statement
  3. Exception handling and method overriding
  4. Exception Propagation
  5. Nested try statements
  6. Difference between Checked exception & Unchecked exception
  7. Java Exception Handling interview questions

You may also like -

No comments:

Post a Comment