Custom Exceptions क्या हैं
In this page:
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
// 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}")
}
}
Login to try C/C++/Java/PHP code in the editor
Adding Extra Properties
एक custom exception एक message से आगे अतिरिक्त properties रख सकता है, catching code को सिर्फ text parse करने के बजाय programmatically काम करने के लिए structured जानकारी देते हुए।
उदाहरण: Adding Extra Properties
// 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}")
}
}
Login to try C/C++/Java/PHP code in the editor
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
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}")
}
}
}
Login to try C/C++/Java/PHP code in the editor
Including a Cause
किसी custom exception का constructor एक cause (एक दूसरा Throwable) भी accept और forward कर सकता है, callers को एक साफ़, ज़्यादा उच्च-स्तरीय exception दिखाते हुए original underlying error को संरक्षित रखते हुए।
उदाहरण: Including a Cause
// 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}")
}
}
Login to try C/C++/Java/PHP code in the editor
Exception(याRuntimeException) के बजाय सीधेThrowableको extend करना, जो application-level errors के लिए लगभग कभी वह नहीं है जो आप असल में चाहते हैं।- superclass constructor को एक message (और optionally एक cause) देना भूल जाना, जिससे print होने पर कोई उपयोगी description न रखने वाले exceptions बनते हैं।
- हर छोटी स्थिति के लिए बहुत 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: