Program : To implement and demonstrate user defined exception.
Algorithm
Step 1: Start
Step 2: create class IllegalMarkException extends Exception
Step 3: create class markprocess
Step 4: Read mm
Step 5: markprocess p=new markprocess()
Step 6: p.validate(mm)
Step 7: p.result(mm)
Step 8: stop
Function validate(int mark)
Step 1: Start
Step 2: if(mark<=0) go to 3 else to 5
Step 3: IllegalMarkException ex=new IllegalMarkException
Step 4: throw ex
Step 5: exit
Function result(int mark)
Step 1: Start
Step 2: if(mark>=40) go to 2 else to 4
Step 3: str=”PASS” go to 5
Step 4: str=”FAIL”
Step 5: print “you have”,str,” ED the exam”
Step 6: exit
Program
import java.io.*; class IllegalMarkException extends Exception { private int mark; IllegalMarkException(int m) { mark=m; } public String toString() { return ("Illegal Mark : " + mark ); } } class MarkProcess { String str; void Validate(int mark) throws IllegalMarkException { if(mark<0) { IllegalMarkException ex=new IllegalMarkException(mark); throw ex; } } String Result(int mark) { if(mark>=40) str="PASSED"; else str="FAILED"; return(str); } } public class MyMarkList { public static void main(String args[]) { int reg[],mark[]; int i,n; String result; DataInputStream in=new DataInputStream(System.in); MarkProcess m=new MarkProcess(); try { System.out.println("Enter number of candidates : "); n=Integer.parseInt(in.readLine()); reg=new int[n]; mark=new int[n]; System.out.println("Enter "+ n +" register numbers :"); for(i=0;i<n;i++) reg[i]=Integer.parseInt(in.readLine()); System.out.println("Enter "+ n +" marks :"); for(i=0;i<n;i++) mark[i]=Integer.parseInt(in.readLine()); System.out.println("Reg No:\t\tMark\tResult "); System.out.println("-------------------------------"); for(i=0;i<n;i++) { System.out.print(reg[i] + "\t\t"+ mark[i] + "\t"); try { m.Validate(mark[i]); result=m.Result(mark[i]); System.out.println(result); } catch (IllegalMarkException e) { System.out.println("Exception :"+e); } } } catch(Exception e) { System.out.println("Error : " + e); } } } |
Output
Enter number of candidates :
6
Enter 6 register numbers :
101
102
103
104
105
106
Enter 6 marks :
25
95
-9
0
55
-2
Reg No: Mark Result
——————————-
101 25 FAILED
102 95 PASSED
103 -9 Exception :Illegal Mark : -9
104 0 FAILED
105 55 PASSED
106 -2 Exception :Illegal Mark : -2