Monday 24 February 2014

Difference between throw and throws

1. The key word throws is used in method declaration, this specify what kind of exception we may expect from this method. The key word throw is used to throw an object that is instance of class Throwable.

2. You can specify multiple exceptions thrown by a method using throws clause, where as throw throws one Throwable object only.

3. throw keyword can be used in switch statement, where as throws only in the method declaration.

Example
class ThrowEx{
 static void throwExceptions(int num){
  switch(num){
   case 1:
    throw new RuntimeException("Exception number 1");
   case 2:
    throw new RuntimeException("Exception number 2");
   case 3:
    throw new RuntimeException("Exception number 3");
   default:
    System.out.println("No Exceptions thrown");
  }
 }

 public static void main(String args[]){
  try{
   throwExceptions(1);
  }
  catch(Exception e){
   System.out.println(e);
  }
 }
}
Output
java.lang.RuntimeException: Exception number 1
  

4. Throw keyword is used to throw exceptions from initializer block
import java.io.*;

class Stack{
 int size;

 {
  try{
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   System.out.println("Enter input");
   size = Integer.parseInt(br.readLine());
  }
  catch(Exception e){
   throw e;
  }
 }

 Stack()throws Exception{
 
 }

 public static void main(String args[]){
  try{
   new Stack();
   
   }
   catch(Exception e){
    System.out.println("Exception caught in main " + e);
   }
 }
}

Sample Output
Enter input
qwe
Exception caught in main java.lang.NumberFormatException: For input string: "qwe"


Note:
1. Static initializers cannot throw checked exceptions
2. Static initializers can throw unchecked exceptions like RuntimeException

throw clause                                                 try-resource statement                                                 Home

No comments:

Post a Comment