Question 9.2:
• Create a exception class named MyException that extend a base class named
Exception
• Design a constructor in your class that accepts a string value set it to the super
class constructor to display the exception message.
• Create a main class named product. Write a method inside the class called
productCheck(int weight) that accepts weight of the product. Inside the method, if
the weight is less than 100 then throw an exception “Product is invalid” otherwise
print the weight of the product.
• Inside the main method declare single object of the product class and call the
productCheck() method to display the weight of the product.
Solution:
package lab9problem2;
import java.util.Scanner;
public class MyException extends Exception{
MyException(String s) {
super(s);
}
}
class Product {
public static void productCheck(int weight) throws MyException {
if (weight < 100) {
throw new MyException("Product is invalid");
} else {
System.out.println(weight);
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("Enter weight: ");
int n = input.nextInt();
Product product = new Product();
try {
product.productCheck(n);
} catch (MyException e) {
System.out.println(e);;
}
}
}
}