सी # में कस्टम अपवाद बनाने का एक आसान तरीका एक सामान्य वर्ग का उपयोग कर रहा है। यदि आपको अधिक अपवाद बनाने की आवश्यकता है तो यह नाटकीय रूप से कोड की रेखाओं को कम कर देता है (यानी यदि आपको अपने यूनिट परीक्षणों में उनके बीच अंतर करने की आवश्यकता है)।
पहले एक सरल CustomException<T>
बुलाया वर्ग बनाने के लिए:
public class CustomException<T> : Exception where T : Exception
{
public CustomException() { }
public CustomException(string message) : base(message){ }
public CustomException(string message, Exception innerException) : base(message, innerException){ }
public CustomException(SerializationInfo info, StreamingContext context) : base(info, context){ }
}
आप के रूप में कई निर्माताओं और तरीकों के रूप में आप चाहते हैं (या जरूरत) ओवरराइड कर सकते हैं।
public class MyCustomException : Exception { }
public class SomeOtherException : Exception { }
आप अपने कस्टम अपवाद उपयोग को बढ़ाने के लिए चाहते हैं: नए अपवाद प्रकार बनाने के लिए सिर्फ नया एक-लाइनर वर्गों को जोड़ने
throw new CustomException<MyCustomException>("your error description");
यह आपके अपवाद कोड सरल रहता है और आप को अलग करने के लिए अनुमति देता है उन अपवादों के बीच:
try
{
// ...
}
catch(CustomException<MyCustomException> ex)
{
// handle your custom exception ...
}
catch(CustomException<SomeOtherException> ex)
{
// handle your other exception ...
}
आप कस्टम अपवाद वर्ग में कस्टम गुण जोड़ सकते हैं, तो क्या आप केवल एक कस्टम अपवाद वर्ग नहीं बना सकते हैं, फिर अपवाद के "प्रकार" के लिए एक एनम जोड़ें? – mellamokb
यदि 'नया अपवाद फेंक दें ("एक आर्बेटरी त्रुटि संदेश");' आपके लिए काम नहीं करेगा, यह समझाने के लिए एक प्रश्न का विस्तार करना एक अच्छा विचार हो सकता है कि क्यों। –
नहीं, ऐसा नहीं होना चाहिए और वहां नहीं होना चाहिए। –