1.

Throw vs Throws keyword in Java

Answer»

Both the throw and throws keywords in Java are related to exception handling. DIFFERENCES between these two keywords are given as follows:

ThrowThrows
An exception is explicitly thrown using the throw keyword.An exception is declared using the throws keyword.
The throw keyword is followed by an instance.The throws keyword is followed by a class.
The throw keyword only cannot propagate a checked exception.The throws keyword can propagate a checked exception.
It is not POSSIBLE to throw multiple exceptions.Multiple exceptions can be declared using throws keyword.
The throw keyword is used WITHIN a method.The throws keyword is used with the method signature.

A program that demonstrates throw keyword in Java is given as follows:

public class Demo {     STATIC void checkMarks(INT marks)   {     if(marks < 40)        throw new ArithmeticException("You failed");       else      System.out.println("Congratulations! You passed");     }   public static void main(String args[])   {      System.out.println("Test Report");      checkMarks(29);    } }

The output of the above program is as follows:

Test Report Exception in thread "main" java.lang.ArithmeticException: You failed at Demo.checkMarks(Demo.java:6) at Demo.main(Demo.java:16)

A program that demonstrates throws keyword in Java is given as follows:

public class Demo {    public static void main(String[] args) throws InterruptedException    {        Thread.sleep(1000);        System.out.println("Demonstration of throws keyword");    } }

The output of the above program is as follows:

Demonstration of throws keyword


Discussion

No Comment Found