//user defined exception in Java
Description
This program demonstrates the working of user defined exception in Java. The class which handles the user defined exception must extend the Exception class, here the class is Empid which contains the constructor Empid(). The class Employee contains the constructor Employee() which takes as input name, department and employee id. The display() function calls the user defined exception if employee id less than or equal to 0, otherwise it will print both these values.
Program
class Empid extends Exception { Empid() //Defining user defined exception { System.out.println("Empid Cannot be negative"); } } class Employee { String name,dept; int empid; public Employee(String name,String dept,int empid) { this.name=name; this.dept=dept; this.empid=empid; } public void display() throws Empid { if(empid <= 0) throw new Empid(); else System.out.println("Emp id= "+empid+" Name= "+name+" Dept= "+dept); } } public class Emp { public static void main(String s[]) { Employee e1=new Employee("Jibin","EC",4); Employee e2=new Employee("Amal","ME",-5); try { e1.display(); e2.display(); } catch(Exception ex) { System.out.println("Error"); } } }
Output
Java: user defined exception |
No comments:
Post a Comment