MY mENU


Thursday 9 February 2012

Difference between Throws and Throw in java


Throws is useful to escape from handling Exception

Throw is useful to create an Exception Class Object and throw it out explicitly.

Advantages of Throw :

1. Throw is used in s/w testing to test a Java Program whether it is handling the Exceptions or not.

2. Throw is useful to create and throw user defined Exceptions

Throw is statement. 

Example:
public static void main(String s[]){
try{
//do ur stuff
}catch(ArithmaticException ae){ //1
s.o.p("caught in main");
}
}

public static int compute(int number){
if(number == 0) throw new ArithmaticException("....");//2
return n;
}

in above program, in 2 exception occur and at 1 it handled

Throws is a clause. Generally useful for checked exception.

Example

public static void main(String s[]){
try{
//do ur stuff
}catch(MyExxception ae){ //1
s.o.p("caught in main");
}
}

public static int compute(int number){
if(number == 0) throw new MyException("....");//2
return n;
}

class MyException extends Exception{
MyException(String str){
super(str);
}
}

No comments:

Post a Comment