Write an assignment on creating your own exception subclass. [CO3] Instructions: (i). Define exception handling in java
Question:
Write an assignment on creating your own exception subclass. [CO3]
Instructions:
(i). Define exception handling in java and the reasons why you should use exception handling in your program perfectly. (ii). Create an exception subclass that can be thrown to handle these kinds of problems during program execution (iii) Find an idea by yourself to design an exception subclass and when to throw it. Your idea may be simple but should be meaningful. (iv). Address the advantages of creating an exception subclass that can be thrown to handle problems during program execution in your java program. (v). It should not be matched with any other students. It should be a unique and meaningful design.
.
Consider the following class InvalidMarksException which extends the Exception class. The InvalidMarksException is thrown when invalid marks (less than zero or greater than one hundred) has been entered as an input.
Now, create an exception subclass that can be thrown to handle these kinds of problems during program execution. Find an idea by yourself to design an exception subclass and when to throw it. Your idea may be simple like the InvalidMarksException, but should be meaningful. Moreover, it should not be matched with any other students. The highest marks will come from a unique and meaningful design.
import java.util.Scanner;
class InvalidMarksException extends Exception {
private int marks;
InvalidMarksException(){}
InvalidMarksException(int i){marks = i;}
@Override
public String toString() {
return "InvalidMarksException: "+marks;
}
}
public class MyException {
static void compute (int value) throws InvalidMarksException {
if(value>100 || value<0) {
throw new InvalidMarksException(value);
}
else
System.out.println("Valid Marks: "+value);
}
public static void main(String[] args) {
int i,value;
Scanner inp = new Scanner(System.in);
for(i=0;i<5;i++) {
try {
value = inp.nextInt();
compute(value);
}catch(InvalidMarksException x) {
System.out.println("Exception Caught: "+x);
}
}
}
}
Business
ISBN: 978-1133595854
12th edition
Authors: William M. Pride, Robert J. Hughes, Jack R. Kapoor