शुरू करेंमुफ़्त में शुरू करें

(Re)Throwing

जब कोई मेथड कोई exception थ्रो करता है, तो उसे कॉल करने वाला मेथड उस exception को handle करे. हैंडल करने के लिए, वह try/catch कर सकता है या उसे फिर से थ्रो कर सकता है. इस अभ्यास में, आप देखेंगे कि कोई calling मेथड exception को कैसे rethrow करता है.

यह अभ्यास पाठ्यक्रम का हिस्सा है

Java में डेटा टाइप्स और Exceptions

पाठ्यक्रम देखें

अभ्यास निर्देश

  • dineOut() मेथड को 9 लोगों के साथ कॉल करें ताकि Exception ट्रिगर हो.
  • चूँकि dineOut() मेथड exception को handle नहीं कर रहा है, Exception को फिर से थ्रो (rethrow) करें.
  • चूँकि splitBill() मेथड exception को handle नहीं कर रहा है, Exception को थ्रो करें.

इंटरैक्टिव व्यावहारिक अभ्यास

इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।

public class RethrowingExample {

	public static void main(String[] args) {
		try {
			// Trigger the exception by calling dineOut with 9 people
			dineOut(____, 50.00);
		} catch (Exception e) {
			System.out.println("Atempting to divide bill with too many diners");
		}
	}

	// Rethrow the Exception
	public static void dineOut(int people, double bill) ____ ____ {
		double each = splitBill(bill, people);
		System.out.println("Bill for each person: " + each);
	}

	// Throw the Exception
	public static double splitBill(double bill, int people) ____ ____ {
		if (people < 3) {
			return bill / people;
		} else {
			throw new Exception();
		}
	}
}
कोड संपादित करें और चलाएँ