Throw & Throws Keyword in Java

Java throw and throws

Both throw and throws are the concepts of exception handing in which throw is used to explicitly throw an exception from a method or any block of code while throws are used in the signature of the method to indicate that this method might throw one of the listed type exceptions.

The key distinctions between throw and throws are as follows.

Java throws:

In Java, a method’s signature might contain the keyword throws, which indicates that the method may throw any of the specified type exceptions. These methods require the caller to use a try-catch block to handle the exception.

Example:

public class throws Keyword{
    public static void main(String[] args) throws InterruptedException {
        Thread.sleep(5000);
                System.out.println("I Love JAVA");
    }

}

When you run this program, it will output:

I Love Java

Example:

public class my_java{
     public int division(int x, int y) throws ArithmeticException{
          int z = x/y;
          return z;
       }
    public static void main(String[] args) {
        my_java obj = new my_java();
          try{
             System.out.println(obj.division(10,0));
          }
          catch(ArithmeticException e){
             System.out.println("You shouldn't divide number by zero");
          }
       
    }
}

When you run this program, it will output:

You should n’t divide number by zero

Java throw:

To explicitly throw an exception from a method or any other piece of code, utilize Java’s throw keyword. Either a checked or unchecked exception may be thrown. Throwing custom exceptions is the primary application of the throw keyword.

Example :

public class throwExample {
   static void fun(){

 try {
    throw new NullPointerException("Demo");
 }
 catch (NullPointerException e) {
    System.out.println("Caught inside fun().");
 throw e; // rethrowing the exception
 }
}

public static void main(String args[]) {

try {
   fun();
}
catch (NullPointerException e) {
   System.out.println("Caught in main.");
   }
}

When you run this program, it will output:

Caught inside fun().

Caught in main

 

 

Visited 1 times, 1 visit(s) today

Comments are closed.

Close