Wednesday, 10 January 2018

Difference between throw and throws in java?

 throw

 throw is used to throw an exception explicitly.

 throw is used in method implementation.

 throw is followed by an instance.

 we can throw only  single exception at a time.

 Syntax:

 throw new exception_name;

 Example:

   public class ThrowExample{

    void check(int num){ 

     if(num%2==0) 
{
       System.out.println("EVEN NUMBER");
}
     else 
{
      throw new ArithmeticException("NOT EVEN");   
   } 

   public static void main(String args[]){ 

       ThrowExample t1=new ThrowExample();
       t1.check(12); 
    
  } 
Output:

//  t1.check(12); 

So output is

EVEN NUMBER

//  t1.check(13); 

So output is

Exception in thread "main" java.lang.ArithmeticException: NOT EVEN
at ThrowExample.check(ThrowExample.java:8)
at ThrowExample.main(ThrowExample.java:12)
Command exited with non-zero status 1

throws

  throws is used to declare an exception.

  throws is used in method signature.

  throws is followed by class

  throws can declare multiple exception at a time like 
void Show()throws IOException,SQLException.

 Syntax:

  return_type method_name() throws exception_class_name
  {  
 //
   }  

 Example:
         

 import java.io.*;

  public class ThrowsExample{

  void Show()throws IOException{
  System.out.println("Welcome to LearningPoint92");
 }
}

 Class demo{

public static void main(String args[])throws IOException{

 ThrowsExample t1=new ThrowsExample();
  t1.Show();

  }
}

Output:


 Welcome to LearningPoint92

No comments:

Post a Comment

apply function in R

1) apply function: It takes 3 arguments matrix,margin and function.. Example: m<-matrix(c(1,2,3,4),nrow=2,ncol=2) m #1 indicates it is ap...