Difference between throw and throws in Java

hello freinds in this article we know about Difference between throw and throws in Java and In this tutorial, well take a glance at the throw and throws in Java. Well make a case foronce weought to use every of them.Next, well show some samples of their basic usage.so read this article carefully.

Throw and Throws

Lets begin with a fast introduction. These keywords are regarding exception-handling. Exceptions are raised once the conventional of flow of our application is disrupted.
There could also be loads of reasons. A user may send the incorrect input data. we will lose a affiliation or different surprising state of affairs may occur. smart exceptions handling may be a key to stay our application operating when an appearance of those unpleasant moments.We use throw keyword to expressly throw an exception from the code. it’s going to be any technique or static block. This exception should be a taxonomic category of Throwable. Also, it is a Throwable itself. we tend to cant throw multiple exceptions with a single throw.

Throws keyword can be placed within the technique declaration. It denotes that exceptions is thrown from this method. We should handle these exceptions with try-catch.

These 2 keywords arent interchangeable!

Read Also : Types of soil in india – Indian Classification of Soils

Difference between throw and throws

[table id=2 /]

Example

public class JavaTester{
   public void checkAge(int age){
      if(age<18)
         throw new ArithmeticException("Not Eligible for voting");
      else
         System.out.println("Eligible for voting");
   }
   public static void main(String args[]){
      JavaTester obj = new JavaTester();
      obj.checkAge(13);
      System.out.println("End Of Program");
   }
}

Output :

Exception in thread "main" java.lang.ArithmeticException:
Not Eligible for voting
at JavaTester.checkAge(JavaTester.java:4)
at JavaTester.main(JavaTester.java:10)
Share on:

Learnitspro is the online learning platform,Here you will find best articles for online learning.

Leave a Comment