24.5 C
New York
Thursday, August 22, 2024

The right way to keep away from exceptions in C#




var end result = Check.DivideNumbers(15, 5);
if (end result.IsSuccess)
    Console.WriteLine($"The result's: {end result.Worth}");
else
    Console.WriteLine($"Error occurred: {end result.ErrorMessage}");

Keep away from exceptions utilizing the Strive-Parse sample

The Strive-Parse sample is one other nice strategy to keep away from exceptions in your software. In C#, the Strive-Parse sample is represented utilizing the TryParse technique, which converts an information kind into one other and returns a Boolean worth. If the parsing course of succeeds, then the output is true, false in any other case. You’ll be able to benefit from this sample to keep away from exceptions in your code whereas changing information varieties as proven within the code snippet given beneath.


String str = "1000";
Boolean end result = Int32.TryParse(str, out int n);
if (end result == true)
    Console.WriteLine($"{n}");
else
    Console.WriteLine("Error in conversion");

Keep away from exceptions by calling Strive* strategies

When changing an information kind to a different, you must benefit from the Strive-Parse sample as proven above. Additional, notice that there are different Strive strategies comparable to TryGetValue. These strategies return false if unsuccessful and return the results of a profitable operation utilizing an out parameter. The next code snippet exhibits how this may be achieved.



Supply hyperlink

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles