package studentage; public class Nage extends Exception { public Nage(String s) { super(s); } };
package verifyage; import studentage.Nage; public class Verify { public void checkage(int a) throws Nage { if(a>0) { System.out.print("valid age"); } else { Nage n=new Nage("Invalid age"); throw(n); } } }
import studentage.Nage; import verifyage.Verify; import java.util.Scanner; public class Main { public static void main(String args[]) { System.out.print("Enter your age : "); Scanner s=new Scanner(System.in); try { int age=s.nextInt(); Verify v=new Verify(); v.checkage(age); System.out.print("your age is : "+age); } catch(Nage ne) { System.out.println("Age should not be Nagetive"); } } }
Enter your age: 20
Valid age
your age is : 20
Enter your age : -20
Age should not be negative.
What is difference between the throws and throw ?
Throws is a keyword used to forward the exception to the method call whereas throw is a keyword used to throw exception to the method sign.
Throws always should be followed by method signature whereas throw keyword always should exist within method only.