← Back to R Course | Chapter 12: Best Practices | Lesson 5 of 6

tryCatch() का उपयोग

tryCatch उस code के लिए एक safety net है जो गलत हो सकता है: कुछ try करें, और अगर यह fail हो crash होने की बजाय एक backup plan चलाएँ। यह आपके program को mistakes gracefully handle करने देता है।

In this page:

  1. tryCatch()
Syntax
r
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()

markup
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")
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. यह भूल जाना कि एक warning, error = से catch नहीं होता, इसलिए इसे एक warning = function(w) handler चाहिए।
  2. expression को tryCatch(...) के बाहर रखना, इसलिए error catch नहीं होती।
  3. error ignore करना और कुछ return न करना, इसलिए caller को नहीं पता चलता कि कुछ गलत हुआ।
🔒

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.