Some simple tips and tricks on Exception handling in C#.
Today in this article we are going to see some tips and tricks to handle exception in C#.
- Don’t use try catch block in every method:- Using try catch block in every method is not going to help you in anyway instead, it makes your program more slow as it has to execute multiple catch blocks for single exception. Put try catch block in parent method and it will work fine. It will handle all the exceptions. Below is the example where try catch block is correctly implemented.
Example:-
Output:-
Student name
fail: SampleDemo.Worker[0]
Student name cannot be empty
As you can see in the above program we are implementing try catch block only in parent function and it is working fine without adding in each method.
2. Use finally block in every try catch block:- As we know that finally block is optional but it is very useful. finally block is always being executed at the end. Use finally block to empty your objects that were created in the function. This will make sure that memory leak won’t happen and it relieves GC of clearing the objects. Because GC has less work to do, automatically your program will use less memory.
Example:-
As you can see in finally block we are making student object as null.
Thank you for reading please comment your suggestions, share the article, follow me and Abhima C# Programming publication.
Bhagavad Gita Verse of the Day
ते तं भुक्त्वा स्वर्गलोकं विशालं
क्षीणे पुण्ये मर्त्यलोकं विशन्ति |
एवं त्रयीधर्ममनुप्रपन्ना
गतागतं कामकामा लभन्ते || 21||
te taṁ bhuktvā swarga-lokaṁ viśhālaṁ
kṣhīṇe puṇye martya-lokaṁ viśhanti
evaṁ trayī-dharmam anuprapannā
gatāgataṁ kāma-kāmā labhante
BG 9.21: When they have enjoyed the vast pleasures of heaven, the stock of their merits being exhausted, they return to the earthly plane. Thus, those who follow the Vedic rituals, desiring objects of enjoyment, repeatedly come and go in this world.