Throws and Throw in Java with Example – Exception Handling

By | December 22, 2010
You can learn about difference between Throws and Throw in Java. In this tutorial you can learn about throws and throw concept with example.

You can learn about difference between Throws and Throw in Java. In this tutorial you can learn about throws and throw concept with example.

class Number{
private int num;
public void accept(int n) throws Exception{
if( n == 0 ){
throw new Exception(“can’t assign zero…”);
}
else if(n < 0){
throw new Exception(“can’t assign -ve value…”);
}
else{
System.out.println(“\n\n\tValid value.”);
num = n;
}
}
}
public class ThrowsDemo{
public static void main(String args[]){
Number ob = new Number();
try{
ob.accept(-8);
//ob.accept(10);
}
catch(Exception e){
System.out.println(“\n Error: ” + e);
}
System.out.println(“\n\n”);
}
}
Result:
Error: java.lang.Exception: can’t assign -ve value…

Leave a Reply

Your email address will not be published. Required fields are marked *