← Back to Core Java Course | Chapter 10: Exception Handling | Lesson 2 of 8

Java में try-catch

try-catch एक safety net जैसा है: आप कुछ risky try करते हैं और, अगर यह fail हो, problem catch करते हैं और calmly respond करते हैं। Program crash नहीं होता।
Syntax
java
try {
    // risky code
} catch (ExceptionType e) {
    // handle e
}

The try Block

try block उस specific code lines को wrap करता है जिन्हें आप suspect करते हैं कि एक exception throw कर सकती हैं। Java सिर्फ तब exceptions के लिए check करना शुरू करता है जब execution इस block में enter करे; इसके बाहर का code protected नहीं है।

उदाहरण: The try Block

java
public class Main {
	public static void main(String[] args) {
		try {
			int result = 10 / 0; // suspected risky code
			System.out.println(result);
		} catch (ArithmeticException e) {
			System.out.println("Error caught");
		}
	}
}

The catch Block

एक catch block एक exception type catch करता है और इसका recovery logic चलाता है अगर paired try के अंदर एक matching exception throw हो। अगर कोई exception न हो, पूरा catch block skip हो जाता है।

उदाहरण: The catch Block

java
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Try code that might throw an exception
		try {
			// Declare result and set it to 10 / 2
			int result = 10 / 2;
			// Print a line to the console
			System.out.println(result);
		// Handle ArithmeticException if it was thrown
		} catch (ArithmeticException e) {
			// Print a line to the console
			System.out.println("This is skipped: no exception occurred");
		}
	}
}

Multiple Catch Blocks

आप एक try के बाद कई catch blocks chain कर सकते हैं अलग-अलग exception types को अलग-अलग handle करने के लिए — एक FileNotFoundException user को एक नई file चुनने को prompt कर सकता है, जबकि एक IOException बस log और retry कर सकता है।

Java उन्हें top से bottom जांचता है और सिर्फ पहला match चलाता है।

उदाहरण: Multiple Catch Blocks

java
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Try code that might throw an exception
		try {
			// Declare arr and set it to new int[2]
			int[] arr = new int[2];
			// Print a line to the console
			System.out.println(arr[5]);
		// Handle ArrayIndexOutOfBoundsException if it was thrown
		} catch (ArrayIndexOutOfBoundsException e) {
			// Print a line to the console
			System.out.println("Index error");
		// Handle NullPointerException if it was thrown
		} catch (NullPointerException e) {
			System.out.println("Null error");
		}
	}
}

Multi-Catch Block

एक multi-catch block (catch (IOException | SQLException e)) एक block को कई unrelated exception types को identically handle करने देता है, duplicated recovery code से बचते हुए जब response दोनों तरह same होता।

Caught variable का type listed exceptions का common supertype है।

उदाहरण: Multi-Catch Block

java
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Try code that might throw an exception
		try {
			// Throw NumberFormatException to signal an error
			throw new NumberFormatException("bad number");
		// Handle NumberFormatException | NullPointerException if it was thrown
		} catch (NumberFormatException | NullPointerException e) {
			// Print a line to the console
			System.out.println("Handled: " + e.getMessage());
		}
	}
}

Nested try-catch Blocks

आप एक दूसरे try block के अंदर एक try-catch nest कर सकते हैं जब एक inner operation को outer block के broader recovery logic से अलग अपना, ज़्यादा specific error handling चाहिए।

यह आम है जब एक single risky call एक बड़े risky operation के अंदर बैठा हो।

उदाहरण: Nested try-catch Blocks

java
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Try code that might throw an exception
		try {
			// Try code that might throw an exception
			try {
				// Declare result and set it to 10 / 0
				int result = 10 / 0;
			// Handle ArithmeticException if it was thrown
			} catch (ArithmeticException e) {
				// Print a line to the console
				System.out.println("Inner catch");
			}
		// Handle Exception if it was thrown
		} catch (Exception e) {
			System.out.println("Outer catch");
		}
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. एक child से पहले एक parent exception catch करना, जो already been caught compile error है।
  2. ऐसा exception catch करना जो try block कभी throw नहीं कर सकता (एक checked वाला), जो एक compile error है।
  3. catch या finally के बिना एक try block उपयोग करना, जो एक compile error है।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.