Difference between throw and throws clause

What is the difference between throw and throws clause, explain programmatically

A program can throw an exception, using throw statement. When an exception is thrown, normal execution is suspended. The runtime system proceeds to find a catch block that can handle the exception. The exceptions are caught under the Exception class. This class is used for giving user defined exception. To use this class throw keyword is used.

//Program using throw keyword

class check_age extends Exception// inheriting the exception class

{

   public String toString()

   {

       return "Age cannot be less than 18";

   }

   static void age(int a)

   {

       try// to handle exception try and catch block is given

       {

           if(a<18)

           {

               check_age obj= new check_age();

               throw obj;// throwing exception using class object

           }

           else

           System.out.println("Adult");

       }

       catch(Exception e)// catch block to give error message

       {

           System.out.println(e);

       }

   }

   public static void main(String args[])

   {

       age(Integer.parseInt(args[0]));

   }

}
However if the user wants to handle the Exception at some point like in other class then the Java provides with the throws statement.

class check_age extends Exception// inheriting the exception class

{

   public String toString()

   {

       return "Age cannot be less than 18";

   }

}

class a

{

   static void age(int a)throws Exception

   {

       if(a<18)

       {

           check_age obj= new check_age();

           throw obj;

       }

       else

       System.out.println("Adult");

   }

   public static void main(String args[])

   {

       try

       {

           a obj1=new a();

           obj1.age(Integer.parseInt(args[0]));

       }

       catch(Exception e)

       {

           System.out.println(e);

       }

   }

}
Tomcat in java and its usage
Tomcat in java and its usage - Tomcat is an open source servlet container. It was developed by Apache Software Foundation. It is commonly known as Apache Tomcat. It is a web server for the processing of JSP and Java Servlets. When a programmer makes web applications by using servlets or JSP then a .war file is made by compressing the application folder...
Difference between Tomcat and Weblogic server
Tomcat and Weblogic server - Tomcat is a web server which can run servlets and JSP whereas Weblogic is an application server which can run EJBs also...
Interface and its implementation
Interface and its implementation - Interface is a set of protocols which are used to define the structure of an application...
Post your comment