← Back to Bash Course | Chapter 12: Error Handling & Debugging | Lesson 8 of 12

Custom Error Handling के लिए trap ERR

trap ERR एक script को script में किसी भी command के fail होने पर अपने आप एक custom block of code run करने देता है, दूसरी languages में catch block जैसा।
Syntax
bash
trap 'commands' ERR
set -e

एक Basic ERR Trap

trap handler ERR code register करता है जो script में एक command fail होने पर अपने आप run होता है, उन्हीं situations में जहां set -e आमतौर पर इसे रोक देता।

उदाहरण: A Basic ERR Trap

bash
#!/bin/bash
(
    trap 'echo "an error was trapped"' ERR
    set -e
    false
    echo "unreached"
) || echo "subshell exited after the ERR trap ran"

Failing Line Number Report करना

एक ERR trap के अंदर, $LINENO उस line number को reflect करता है जहां failure हुई, जो actual bug pinpoint करने के लिए error messages को कहीं ज़्यादा उपयोगी बनाता है।

उदाहरण: Reporting the Failing Line Number

bash
#!/bin/bash
(
    trap 'echo "error occurred near line $LINENO"' ERR
    set -e
    true
    false
) || echo "handled"

ERR Traps को Functions के अंदर काम करने देना

By default, एक ERR trap functions या command substitutions के अंदर propagate नहीं होता। set -o errtrace (equivalently set -E) trap को extend करता है ताकि यह चाहे failure कहीं भी हो, fire हो।

उदाहरण: Making ERR Traps Work Inside Functions

bash
#!/bin/bash
(
    set -E -e
    trap 'echo "caught failure inside a function"' ERR
    fail_inside() {
        false
    }
    fail_inside
    echo "unreached"
) || echo "subshell stopped after the function's failure was trapped"
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. यह मान लेना कि trap ERR उन commands के लिए भी fire होता है जो set -e से exempt हैं (जैसे एक if condition); यह वही exemptions share करता है।
  2. यह भूल जाना कि trap ERR तभी reliably fire होता है जब उस command के लिए set -e semantics effect में हों; अन्यथा functions जैसे contexts में behavior inconsistent हो सकता है जब तक set -E (errtrace) भी उपयोग न किया जाए।
  3. एक ERR handler लिखना जो खुद fail हो सकता है, confusing recursive या missed error handling का कारण बनते हुए।
चैप्टर सारांश
  • trap handler ERR handler run करता है जब भी एक command fail हो, उन्हीं contexts में जहां set -e trigger होता।
  • set -o errtrace (set -E) ERR trap को functions और subshells के अंदर भी fire करता है, सिर्फ top-level commands में नहीं।
  • एक ERR trap आमतौर पर script exit होने से पहले diagnostic information (जैसे $LINENO के through failing line number) log करने के लिए उपयोग किया जाता है।
  • trap ERR को एक EXIT trap के साथ combine करना error-specific logging को general cleanup से अलग करने देता है जो हमेशा run होना चाहिए।

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.