Answer to Question #257439 in Java | JSP | JSF for shifa

Question #257439

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".

1
Expert's answer
2021-10-27T06:47:30-0400
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");
			
		}


	}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS