0% found this document useful (0 votes)
5 views

Assignment 1

Uploaded by

Alvee Islam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Assignment 1

Uploaded by

Alvee Islam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

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;

class InvalidMarksException extends Exception{

int marks;
InvalidMarksException(int a){
marks = a;
}
public String toString(){
return "InvalidMarksException: "+marks;
}
}
public class MyExcepEx {

static void compute(int marks) throws InvalidMarksException {


if(marks > 100 || marks < 0)
throw new InvalidMarksException(marks);
else {
System.out.print("Marks obtained: "+marks+" Result: ");
if(marks>=50) System.out.println("Passed");
else System.out.println("Failed");
}

public static void main(String[] args) {

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

You might also like