begin / rescue / ensure का इस्तेमाल
begin, rescue, और ensure एक safety net बनाते हैं: कुछ risky try करें, अगर यह fail हो problem rescue करें, और ensure cleanup हमेशा होना सुनिश्चित करे। यह program को crash होने से रोकता है।
In this page:
Syntax
begin
# code that may fail
rescue ExceptionType => e
# handle e.message
ensure
# always runs
end
begin / rescue / ensure
begin ... rescue ExceptionType => e ... ensure ... end Ruby का exception handling block है: begin में risky code होता है, rescue एक specific exception type handle करता है (या unspecified होने पर कोई भी exception), और ensure हमेशा बाद में चलता है चाहे कोई error हुआ हो या नहीं।
यह दूसरी languages में try/catch/finally को mirror करता है, लेकिन अलग keyword names इस्तेमाल करता है। Methods explicit begin keyword के बिना एक implicit begin/rescue भी इस्तेमाल कर सकते हैं।
Note:
एक method definition खुद directly rescue/ensure clauses रख सकता है, पूरी body को एक explicit begin block में wrap किए बिना।
उदाहरण: begin / rescue / ensure
begin
result = 10 / 0
rescue ZeroDivisionError => e
puts "Caught: #{e.message}"
ensure
puts "Cleanup always runs"
end
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. #}
आम गलतियां
rescue Exceptionसे सब कुछ rescue करना, जो signals और exit भी catch करता है;rescue StandardErrorइस्तेमाल करें।- यह भूल जाना कि
ensureएक error के बाद भी चलता है, और वहाँ ऐसा code रखना जिसे सिर्फ success पर चलना चाहिए। - गलत class के साथ
rescueलिखना, जैसे एकZeroDivisionErrorके लिएArgumentError, इसलिए error catch नहीं होती।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: