Assignment 1
Assignment 1
An exception is an abnormal condition that arises in a code sequence at run time. Java
provides powerful features for exception handling. Although Java’s built-in exceptions handle
most common exceptions, you will probably want to create your own exception types to
handle situations specific to your applications. This is quite easy to do: just define a subclass
of Exception.
Consider the following practical example where a user defined exception subclass has been
designed and used for taking marks data input. An object of the user defined exception
subclass InvalidMarksException has been thrown when the given marks is found to be
invalid, i.e., greater than 100 or less than 0. Obviously, this example has been used to
demonstrate, and you cannot use this as your solution.
Your task will be to design and apply your own exception subclass. The designed exception
subclass and its use must be practical (i.e., resemble with real-life). Don't copy any design
from the class/lab lectures or books/online or from others. The more unique the idea, the
closer to full marks it gets.
Take care of the followings:
I. Design one class as your own exception subclass (i.e., which extends the Exception
class). Use at least one variable, one parameterized constructor and a toString method
inside the subclass.
II. Design a driver class and the main method inside it. Inside this class, apply your
designed exception for a practical need as explained in the following example.
Submission Format: Submit your java program file. File name should be Assignment1_your-id.java
import java.util.Scanner;
int marks;
InvalidMarksException(int a){
marks = a;
}
public String toString(){
return "InvalidMarksException: "+marks;
}
}
public class MyExcepEx {
int i,marks;
Scanner inp = new Scanner(System.in);
for(i=0;i<5;i++){
marks = inp.nextInt();
try{
compute(marks);
}catch(InvalidMarksException e){
System.out.println("Exception Caught: "+e);
}
}
inp.close();
}
}
Output:
70
Marks obtained: 70 Result: Passed
150
Exception Caught: InvalidMarksException: 150
25
Marks obtained: 25 Result: Failed
-5
Exception Caught: InvalidMarksException: -5
95
Marks obtained: 95 Result: Passed