Write a program to handle negative salary exception

Write a program to handle negative salary exception

Write a program to handle negative salary exception

1.Exception Creation Program
package employeesalary;
public class Nsalary extends Exception
{
    public Nsalary(String s)
    {
        super(s);
    }
};

2.Exception verification Program
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);
        }
    }
}

3.Main Program
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");
        }
    }
}


Output:

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.


Exception Handling In Java



More Questions


171 . Write a program to handle negative salary exception
172 . Write a Simple interest program to handle negative amount and duration and interest using user defined exception
173 . Write a String length program
174 . Write a string charAt() method program
175 . Write a string toLowerCase() Program
176 . Write a String toUpperCase() program
177 . Write a string concat() program
178 . Write a string compareTo program
179 . Write a string compareToIgnoreCase() Program
180 . Write a string equals program
181 . Write a string equalsIgnoreCase() program