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

Java के कस्टम Exceptions

एक custom exception एक error type है जो आप खुद एक नाम से बनाते हैं जो आपके program को fit करे, आपके अपने playground के लिए एक special warning sign जैसा। यह problems को clearer बनाता है।
Syntax
java
class CustomException extends Exception {
    public CustomException(String message) {
        super(message);
    }
}

Why Custom Exceptions?

Custom exceptions आपको domain-specific failures को एक meaningful नाम से represent करने देते हैं, जैसे InsufficientFundsException, callers को एक generic RuntimeException message string interpret करने पर मजबूर करने के बजाय।

उदाहरण: Why Custom Exceptions?

java
// Define the class InsufficientFundsException
class InsufficientFundsException extends RuntimeException {
	InsufficientFundsException(String message) {
		// Call the parent class constructor
		super(message);
	}
}
// 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 InsufficientFundsException to signal an error
			throw new InsufficientFundsException("Not enough balance");
		// Handle InsufficientFundsException if it was thrown
		} catch (InsufficientFundsException e) {
			// Print a line to the console
			System.out.println(e.getMessage());
		}
	}
}

Creating Unchecked Custom Exceptions

RuntimeException extend करना एक unchecked custom exception बनाता है, मतलब callers इसे catch या declare करने के लिए compiler-forced नहीं — programming errors के लिए appropriate जिन्हें normally mid-flow recover नहीं किया जाना चाहिए।

उदाहरण: Creating Unchecked Custom Exceptions

java
class InvalidAgeException extends RuntimeException { // unchecked: no forced catch
	InvalidAgeException(String message) {
		super(message);
	}
}
public class Main {
	public static void main(String[] args) {
		throw new InvalidAgeException("Age must be positive");
	}
}

Creating Checked Custom Exceptions

सीधे Exception extend करना एक checked custom exception बनाता है, हर caller को explicitly इसे handle या re-declare करने पर मजबूर करते हुए — expected, recoverable failure conditions के लिए appropriate जैसे एक file genuinely मौजूद न होना।

उदाहरण: Creating Checked Custom Exceptions

java
class InvalidFileException extends Exception { // checked: must be handled or declared
	InvalidFileException(String message) {
		super(message);
	}
}
public class Main {
	static void open() throws InvalidFileException {
		throw new InvalidFileException("File not found");
	}
	public static void main(String[] args) {
		try {
			open();
		} catch (InvalidFileException e) {
			System.out.println(e.getMessage());
		}
	}
}

Adding Custom Fields and Methods

आप एक custom exception में extra fields जोड़ सकते हैं, जैसे एक error code या failure का कारण बनने वाली invalid value, catch blocks को एक bare message string से कहीं ज़्यादा काम करने लायक देते हुए।

उदाहरण: Adding Custom Fields and Methods

java
// Define the class InvalidAgeException
class InvalidAgeException extends RuntimeException {
	int invalidValue;
	InvalidAgeException(String message, int invalidValue) {
		// Call the parent class constructor
		super(message);
		this.invalidValue = invalidValue;
	}
}
// 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 InvalidAgeException to signal an error
			throw new InvalidAgeException("Invalid age", -5);
		// Handle InvalidAgeException if it was thrown
		} catch (InvalidAgeException e) {
			// Print a line to the console
			System.out.println(e.getMessage() + ": " + e.invalidValue);
		}
	}
}

Throwing and Catching Custom Exceptions

एक बार defined होने पर, एक custom exception throw new MyException(...) से एक built-in वाले की तरह throw होता है, और उस specific type का नाम लेते एक catch block से वैसे ही catch होता है।

उदाहरण: Throwing and Catching Custom Exceptions

java
// Define the class InvalidAgeException
class InvalidAgeException extends RuntimeException {
	InvalidAgeException(String message) {
		// Call the parent class constructor
		super(message);
	}
}
// Define the class Main
public class Main {
	static void checkAge(int age) {
		// Check whether age < 0
		if (age < 0) {
			// Throw InvalidAgeException to signal an error
			throw new InvalidAgeException("Age cannot be negative");
		}
	}
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Try code that might throw an exception
		try {
			checkAge(-1);
		// Handle InvalidAgeException if it was thrown
		} catch (InvalidAgeException e) {
			System.out.println("Caught: " + e.getMessage());
		}
	}
}
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. Exception extend करना जब आपका मतलब एक unchecked exception था, इसलिए callers को इसे handle करना चाहिए।
  2. Message को super(message) में pass करना भूल जाना।
  3. उन cases के लिए custom exceptions बनाना जहां एक standard जैसे IllegalArgumentException काफी है।

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.