1.

Role of throw and throws keyword in Java

Answer»

Both the throw and throws keywords in Java are related to exception handling. Details about these are given as follows:

The throw keyword

An exception can be thrown explicitly from a METHOD or a code block using the throw keyword. Mainly custom exceptions are thrown using this keyword. ALSO, throw can be used to throw checked or unchecked exceptions.

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)The throws keyword

The signature of a method can CONTAIN the throws keyword to signify that the specified method can throw any one of the listed type exceptions. The exception can be handled using a try catch block by the caller of the method.

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