← Back to Ruby Course | Chapter 11: File I/O & Exceptions | Lesson 3 of 6

begin / rescue / ensure का इस्तेमाल

begin, rescue, और ensure एक safety net बनाते हैं: कुछ risky try करें, अगर यह fail हो problem rescue करें, और ensure cleanup हमेशा होना सुनिश्चित करे। यह program को crash होने से रोकता है।

In this page:

  1. begin / rescue / ensure
Syntax
ruby
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

markup
begin
  result = 10 / 0
rescue ZeroDivisionError => e
  puts "Caught: #{e.message}"
ensure
  puts "Cleanup always runs"
end
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. rescue Exception से सब कुछ rescue करना, जो signals और exit भी catch करता है; rescue StandardError इस्तेमाल करें।
  2. यह भूल जाना कि ensure एक error के बाद भी चलता है, और वहाँ ऐसा code रखना जिसे सिर्फ success पर चलना चाहिए।
  3. गलत class के साथ rescue लिखना, जैसे एक ZeroDivisionError के लिए ArgumentError, इसलिए error catch नहीं होती।
🔒

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.