2009-09-22 12 views
19

निम्नलिखित कोडरूबी में त्रुटि प्रकार कैसे प्रदर्शित करें?

begin 
raise StandardError, 'message' 
#some code that raises a lot of exception 
rescue StandardError 
#handle error 
rescue OtherError 
#handle error 
rescue YetAnotherError 
#handle error 
end 

मैं एक चेतावनी प्रकार और बचाव खंड के प्रत्येक के लिए प्रिंट बयान जोड़े बिना त्रुटि के बताने वाले संदेश के प्रिंट करना चाहते हैं,

begin 
raise StandardError, 'message' 
#some code that raises a lot of exception 
rescue StandardError 
#handle error 
rescue OtherError 
#handle error 
rescue YetAnotherError 
#handle error 
??? 
print "An error of type #{???} happened, message is #{???}" 
end 

उत्तर

44
begin 
    raise ArgumentError, "I'm a description" 
rescue Exception => ex 
    puts "An error of type #{ex.class} happened, message is #{ex.message}" 
end 

की तरह में प्रिंट: प्रकार की त्रुटि ArgumentError हुई, संदेश है मैं एक विवरण

+3

और फिर यदि आपको अभी भी विभिन्न प्रकार की त्रुटियों के लिए विशिष्ट हैंडलिंग की आवश्यकता है, तो आप कर सकते हैं कि एक मामले के साथ .. जब। – cpm

+3

इसे देखें, अपवाद को तब तक न पकड़ें जब तक कि आप इसका तात्पर्य नहीं जानते कि इसका क्या अर्थ है। एक डिफ़ॉल्ट कैचर के रूप में बचाव => पूर्व के बजाय (कॉन्फ़िगरेशन पर सम्मेलन) का उपयोग करें। –

संबंधित मुद्दे