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

Throws

जब कोई exception थ्रो होती है, तो कोई method या तो उसे try-catch से संभाल सकता है या उसे अपने caller को आगे थ्रो कर सकता है (जिम्मेदारी आगे बढ़ाना). इस अभ्यास में, आप देखेंगे कि try/catch से संभालने के बजाय exception को कैसे थ्रो किया जाता है।

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

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

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

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

  • getScore(3) कॉल करने और उसका आउटपुट प्रिंट करने वाले कोड के चारों ओर एक try ब्लॉक जोड़ें।
  • getScore() मेथड में होने वाली ArrayIndexOutOfBoundsException को संभालने के लिए एक catch ब्लॉक जोड़ें।
  • getScore(int) में try/catch करने के बजाय ArrayIndexOutOfBoundsException को थ्रो करवाएँ।

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

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

package exceptions;

public class ThrowingExample {

	public static int[] scores = { 75, 97, 83 };

	public static void main(String[] args) {
		// Add a try block
		____ {
			int lastScore = getScore(3);
			System.out.println("Last score:" + lastScore);
		// Catch the exception thrown by getScore(int)
		} ____ (____ e) {
			System.out.println("Tried to access non-existent score");
		}
	}

	// Throw ArrayIndexOutOfBoundsException
	public static int getScore(int index) ____ ____ {
		return scores[index];
	}
}
कोड संपादित करें और चलाएँ