Try-catch
संभावित arithmetic exception — शून्य से भाग — को पकड़ें और एक संदेश दिखाकर उसे हैंडल करें. आपको BigDecimal पैकेज का और उपयोग भी देखने का मौका मिलेगा, जो आपके लिए पहले से लोड किया गया है.
यह अभ्यास पाठ्यक्रम का हिस्सा है
Java में डेटा टाइप्स और Exceptions
अभ्यास निर्देश
- एक
tryजोड़ें औरtryकोड ब्लॉक की शुरुआत करें. (ArithmeticException e)के साथArithmeticExceptionको catch करें और एकcatchकोड ब्लॉक शुरू करें.catchकोड ब्लॉक को पूरा करें.
इंटरैक्टिव व्यावहारिक अभ्यास
इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।
class SplitTheBill {
public static void main(String[] args) {
BigDecimal bill = new BigDecimal(125.50);
computeEachBill(bill, 5);
computeEachBill(bill, 0);
}
public static void computeEachBill(BigDecimal bill, int people) {
// Add a try and the beginning of the try code block
____ ____
BigDecimal numPeople = new BigDecimal(people);
BigDecimal individualBill = bill.divide(numPeople);
System.out.println("Bill for each person is: " + individualBill);
// End the try code block and catch a possible ArithmeticException
____ ____ (ArithmeticException e) ____
System.out.println("You didn't provide a positive number of people to split the bill among.");
// End the catch code block
____
}
}