Write an assignment on creating your own exception subclass. Instructions: (i). Define exception handling in java and the reasons why you should use exception handling
Write an assignment on creating your own exception subclass.
Instructions:
(i). Define exception handling in java and the reasons why you should use exception handling in your program perfectly. (ii). Create exception subclass
that can be thrown to handle this kind 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 this kind 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 Invalid Marks Exception but should be meaningful. Moreover, it should not be
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.45 Rating (152 Votes )
There are 3 Steps involved in it
Step: 1
Exception is a abnormal condition means it disrupts and stops the normal flow of execution for example public class Test11 public static void mainString args int b200 It abort the program Systemoutpri...See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started