Monday 24 February 2014

using throws : Specifying the Exceptions Thrown by a Method

Some times it is better to handle the exceptions using catch block, Some times it is better to throw the exception from the method without handling. Use the throws clause to throw an exception from a method.

How to thrown an Exception from a method
methodName(parameters) throws Exception1, Exception2 … ExceptionN

As you see the syntax, a method can throw any number of exceptions. Since constructor is also a special kind of method, so it can also throws exceptions.

Example
import java.io.*;
class ThrowsEx{
 static void print()throws Exception{
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  System.out.println("Enter input");
  int var1 = Integer.parseInt(br.readLine());
  System.out.println(var1);
 }

 public static void main(String args[]){
  try{
   print();
  }
  catch(Exception e){
   System.out.println("Conversion error " + e);
  }
 }
}

When you run the above program by giving valid number, then program runs fine without throwing any error.
Output1
Enter input
12
12

If you gave any non number input, then the method print() throws "NumberFormatException" which is handled in the main method.

Output 2
Enter input
qwe
Conversion error java.lang.NumberFormatException: For input string: "qwe"

finally block                                                 throw clause                                                 Home

No comments:

Post a Comment