Exception Handling snippet – throw(s) (Java)
April 27, 2016
Categorised in: Java Codes
//******************* Employee.java ******************* public class Employee { private int ID; private int Salary; private String Name; public Employee(int ID, int Salary, String Name) throws NegativeSalaryException { this.ID = ID; this.Name = Name; if(Salary<0) throw new NegativeSalaryException(Salary, "You have entered negative salary"); this.Salary = Salary; } @Override public String toString() { // TODO Auto-generated method stub return "Name: "+ Name + " ID: "+ ID + " Salary: "+ Salary; } } //******************* Main.java ******************* public class Main { public static void main(String[] args) throws NegativeSalaryException { Employee employee = new Employee(111, -1000, "Pratik"); System.out.println(employee); } } //******************* NegativeSalaryException.java ******************* public class NegativeSalaryException extends Exception { private int sal; private String exMsg; public NegativeSalaryException(int sal, String exMsg) { this.sal = sal; this.exMsg = exMsg; } @Override public String toString() { // TODO Auto-generated method stub return "\n Salary: " + sal + "\n ExMsg: " + exMsg; } }
Output:
Exception in thread “main”
Salary: -1000
ExMsg: You have entered negative salary
at Employee.<init>(Employee.java:12)
at Main.main(Main.java:6)
Pratik Kataria is currently learning Springboot and Hibernate.
Technologies known and worked on: C/C++, Java, Python, JavaScript, HTML, CSS, WordPress, Angular, Ionic, MongoDB, SQL and Android.
Softwares known and worked on: Adobe Photoshop, Adobe Illustrator and Adobe After Effects.