Write a program to create your own Exception subclass. You need to also override toString() method to define a tailor made description of your own Exception subclass. Then create a class where an exception of the created Exception subclass is thrown by using throw keyword. You need to define a try and catch block to handle the exception in the main method. Finally, after the exception is handled, print "Exception Handling Completed".
import java.util.Scanner;
class PriceException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
public PriceException() {
}
public String toString() {
return "Wrong price!!!";
}
}
public class App {
@SuppressWarnings("resource")
private static void getPrice() throws PriceException {
Scanner keyBoard = new Scanner(System.in);
System.out.print("Enter cost price of item: ");
double costPrice = keyBoard.nextDouble();
if (costPrice <= 0) {
throw new PriceException();
}
keyBoard.close();
}
public static void main(String[] args) {
try {
getPrice();
} catch (PriceException e) {
System.out.println(e.toString());
System.out.println("Exception Handling Completed");
}
}
}
Comments
Leave a comment