Techoceanhub logo

Let’s see throw, throws keyword in Exception Handling.

We have heard about throw and throws keyword in Exception handling, which tends to be important part of handling an exception.
  1. In simple terms throws keyword is used in method declaration to show that this type of exception might occour.
  2. When we talk about throw keyword which is used to throw one exception and it is also used for custom defined exception.
 

Above diagram clearly explains the throw and throws keyword and now lets discuss the differences between throw and throws.

Throw

  • Throw keyword is used inside the function  or inside a block of code.
  • In throw keyword exceptions must be of type throwable class.
  • We can throw only single exception at a time.

Throws

  • This  keyword is used with method signature and declares an exception , which might be thrown by a method.
  • We can declare multiple exceptions with throws keyword.
  • Throws keyword declares an exception.

Now let us see the basic example of throw and throws keyword.

 

package multipleCatch;

public class Multiple{

public static void main(String[] args)throws ArithmeticException {
     int a=5,b=0,c;
    try {
       c=a/b;
    }
   catch(Exception e) {
    System.out.println(“exception is “+e);
    }
 }
 }

 

package multipleCatch;

public class Multiple{
    int a=5,b=0,c;
    void checkException() {
        c=a/b;
         try {
          throw new ArithmeticException(“not allowed”);
          }
         catch(Exception e) {
            System.out.println(e);
         }
     }
    public static void main(String[] args){
          Multiple multiple=new Multiple();
          multiple.checkException();
     }
}

 

Feel free to try this example and comment below.

Share:

Categories

Archives

Related Posts

Array Destructuring

Array Destructuring Array destructuring is a powerful syntax introduced in ES6 that allows you to unpack elements from an array

Read More »

Explore our Affiliated partner links

hostgator website plan

Hostgator

Best Website hosting plans & Best for 24/7 support.

hostinger webhosting plan

Hostinger

Reasonable website hosting packages for small business & 24/7 Email support

Elementor pro

Design Worpdress website quickly using Elementor Builder and AI

buy elementor website templates

Buy Elementor Website Template

Buy ready made Elementor Website Template from us & Get Free Elementor pro licence for 1 year .