← Back to Kotlin Course | Chapter 13: Error Handling & Testing | Lesson 2 of 6

Custom Exceptions क्या हैं

एक custom exception आपकी अपनी नामित तरह की error है, ताकि आपका program बिल्कुल बता सके कि आपके अपने शब्दों में क्या गलत हुआ।
Syntax
kotlin
class CustomException(message: String) : Exception(message)

class DetailedException(val field: Type, message: String) : Exception(message)

throw CustomException("message")

Declaring a Custom Exception

एक custom exception class Exception (या इसकी एक subclass) को extend करती है, आमतौर पर एक message को superclass constructor को forward करते हुए ताकि इसे किसी भी built-in exception की तरह print और inspect किया जा सके।

उदाहरण: Declaring a Custom Exception

markup
// Define a class `InsufficientFundsException`
class InsufficientFundsException(message: String) : Exception(message)

// Define the function `withdraw` taking `balance`, `amount` and returning a Double
fun withdraw(balance: Double, amount: Double): Double {
    if (amount > balance) throw InsufficientFundsException("Cannot withdraw $amount from balance $balance")
    // Return `balance - amount` from this function
    return balance - amount
}

// Entry point: execution of the program starts here
fun main() {
    try {
        withdraw(100.0, 150.0)
    } catch (e: InsufficientFundsException) {
        // Print "Error: ${e.message}" to the console, with a trailing newline
        println("Error: ${e.message}")
    }
}

Adding Extra Properties

एक custom exception एक message से आगे अतिरिक्त properties रख सकता है, catching code को सिर्फ text parse करने के बजाय programmatically काम करने के लिए structured जानकारी देते हुए।

उदाहरण: Adding Extra Properties

markup
// Define a class `ValidationException`
class ValidationException(val field: String, message: String) : Exception(message)

// Define the function `validateAge` taking `age`
fun validateAge(age: Int) {
    if (age < 0) throw ValidationException("age", "Age cannot be negative")
}

// Entry point: execution of the program starts here
fun main() {
    try {
        validateAge(-5)
    } catch (e: ValidationException) {
        // Print "Invalid field ${e.field}: ${e.message}" to the console, with a trailing newline
        println("Invalid field ${e.field}: ${e.message}")
    }
}

Building a Hierarchy of Custom Exceptions

संबंधित custom exceptions एक common open base class share कर सकते हैं, calling code को यह उसकी ज़रूरी precision के आधार पर एक specific exception type या ज़्यादा general base type catch करने देते हुए।

उदाहरण: Building a Hierarchy of Custom Exceptions

markup
open class AppException(message: String) : Exception(message)
// Define a class `NetworkException`
class NetworkException(message: String) : AppException(message)
// Define a class `DatabaseException`
class DatabaseException(message: String) : AppException(message)

// Entry point: execution of the program starts here
fun main() {
    // Declare a read-only variable `errors`, set to `listOf(NetworkException("Timeout"), DatabaseException("Connection lost"))`
    val errors = listOf(NetworkException("Timeout"), DatabaseException("Connection lost"))
    // Loop over `errors`, binding each item to `error`
    for (error in errors) {
        try {
            throw error
        } catch (e: AppException) {
            // Print "App error: ${e.message}" to the console, with a trailing newline
            println("App error: ${e.message}")
        }
    }
}

Including a Cause

किसी custom exception का constructor एक cause (एक दूसरा Throwable) भी accept और forward कर सकता है, callers को एक साफ़, ज़्यादा उच्च-स्तरीय exception दिखाते हुए original underlying error को संरक्षित रखते हुए।

उदाहरण: Including a Cause

markup
// Define a class `DataLoadException`
class DataLoadException(message: String, cause: Throwable) : Exception(message, cause)

// Entry point: execution of the program starts here
fun main() {
    try {
        try {
            throw NumberFormatException("bad number")
        } catch (e: NumberFormatException) {
            throw DataLoadException("Failed to load data", e)
        }
    } catch (e: DataLoadException) {
        // Print "${e.message}, caused by: ${e.cause?.message}" to the console, with a trailing newline
        println("${e.message}, caused by: ${e.cause?.message}")
    }
}
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 (या RuntimeException) के बजाय सीधे Throwable को extend करना, जो application-level errors के लिए लगभग कभी वह नहीं है जो आप असल में चाहते हैं।
  2. superclass constructor को एक message (और optionally एक cause) देना भूल जाना, जिससे print होने पर कोई उपयोगी description न रखने वाले exceptions बनते हैं।
  3. हर छोटी स्थिति के लिए बहुत specific exception subclasses बनाना बजाय अच्छी तरह designed, मायने रखने वाले exception types की एक छोटी संख्या उपयोग करने के।
चैप्टर सारांश
  • एक custom exception आमतौर पर class MyException(message: String) : Exception(message) के रूप में declare होता है।
  • Exception (एक checked-style base, हालांकि Kotlin checked exceptions enforce नहीं करता) या RuntimeException दोनों आम choices हैं।
  • Custom exceptions सिर्फ एक message से आगे अतिरिक्त properties रख सकते हैं, programmatic error handling के लिए उपयोगी।
  • custom exceptions का एक अच्छी तरह designed set उन्हें catch करने वाले code को स्पष्ट रूप से failure reasons बताता है।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

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.