package interest; public class Ninterest extends Exception { public Ninterest(String s) { super(s); } };
package verifyinterest; import interest.Ninterest; public class Verify { public void checkinterest(int a,int d,int i) throws Ninterest { if(a>0 && d>0 && i>0) { System.out.print("valid Numbers"); } else { Ninterest n=new Ninterest("Invalid Numbers"); throw(n); } } }
import interest.Ninterest; import verifyinterest.Verify; import java.util.Scanner; public class Main { public static void main(String args[]) { int a,i,d,si; Scanner s=new Scanner(System.in); try { System.out.print("Enter your Amount : "); a=s.nextInt(); System.out.print("Enter your Duration : "); d=s.nextInt(); System.out.print("Enter your Interest : "); i=s.nextInt(); Verify v=new Verify(); v.checkinterest(a,d,i); si=a*d*i/100; System.out.print("Simple Interest is : "+si); } catch(Ninterest ne) { System.out.println("Amount and Duration and interest should not be Negative"); } } }
Enter your Amount : 2000
Enter your Duration : 2
Enter your Interest : 2
Valid Numbers
Simple Interest is : 80
Enter your Amount : -2000
Enter your Duration : -2
Enter your Interest : 2
Amount and Duration and interest 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.