tryCatch() का उपयोग
tryCatch उस code के लिए एक safety net है जो गलत हो सकता है: कुछ try करें, और अगर यह fail हो crash होने की बजाय एक backup plan चलाएँ। यह आपके program को mistakes gracefully handle करने देता है।
In this page:
Syntax
result <- tryCatch({
expression
}, error = function(e) {
# handle error
}, finally = {
# always runs
})
tryCatch()
tryCatch(expr, error = function(e) ...) एक expression चलाता है और आपको एक error gracefully handle करने देता है बजाय इसके script crash करने के, दूसरी languages में try/catch जैसा।
यह warning और finally handlers भी support करता है। उन scripts के लिए यह essential है जो ऐसा data process करते हैं जो कभी-कभी malformed हो सकता है, पूरी तरह रुकने की बजाय इन्हें जारी रहने देते हुए।
Note:
error handler खुद error object receive करता है, इसलिए इसके अंदर e$message आपको underlying error text देता है।
उदाहरण: tryCatch()
safe_divide <- function(a, b) {
tryCatch({
if (b == 0) stop("Division by zero")
a / b
}, error = function(e) {
cat("Error caught:", e$message, "\n")
NA
})
}
cat(safe_divide(10, 2), "\n")
cat(safe_divide(10, 0), "\n")
Login to try C/C++/Java/PHP code in the editor
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. #}
आम गलतियां
- यह भूल जाना कि एक
warning,error =से catch नहीं होता, इसलिए इसे एकwarning = function(w)handler चाहिए। - expression को
tryCatch(...)के बाहर रखना, इसलिए error catch नहीं होती। - error ignore करना और कुछ return न करना, इसलिए caller को नहीं पता चलता कि कुछ गलत हुआ।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: