Please disable adblock to view this page.

← Go home

Exception Handling snippet – throw(s) (Java)

April 27, 2016
Published By : Pratik Kataria
Categorised in:

//******************* 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)

View Article Page
Download

Pratik Kataria is a budding programmer, web designer and developer.