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
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);
}
}
}
}
Step by Step Solution
3.41 Rating (157 Votes )
There are 3 Steps involved in it
When we write codes and programs it is very much possible that we will make mistakes and those ... View full answer
Get step-by-step solutions from verified subject matter experts
Document Format (2 attachments)
635d5d9cea3ea_174924.pdf
180 KBs PDF File
635d5d9cea3ea_174924.docx
120 KBs Word File
