package employeesalary; public class Nsalary extends Exception { public Nsalary(String s) { super(s); } };
package verifysalary; import employeesalary.Nsalary; public class Verify { public void checkasalary(int a) throws Nsalary { if(a>0) { System.out.print("valid salary"); } else { Nsalary n=new Nsalary("Invalid salary"); throw(n); } } }
import employeesalary.Nsalary; import verifysalary.Verify; import java.util.Scanner; public class Main { public static void main(String args[]) { System.out.print("Enter your Salary : "); Scanner s=new Scanner(System.in); try { int salary=s.nextInt(); Verify v=new Verify(); v.checkasalary(salary); System.out.print("your salary is : "+salary); } catch(Nsalary ne) { System.out.println("salary should not be Negative"); } } }
Enter your Salary: 20000
Valid Salary
your Salary is : 20000
Enter your Salary : -20000
Salary 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.