C
C#8mo ago
Livid

✅ try catch

hey for example (i know tryparse exists)
var str1 = "123"
var str2 = "0ab"
var str3 = "65_"

var int1 = Convert.ToInt32(str1)
var int2 = Convert.ToInt32(str2)
var int3 = Convert.ToInt32(str3)
var str1 = "123"
var str2 = "0ab"
var str3 = "65_"

var int1 = Convert.ToInt32(str1)
var int2 = Convert.ToInt32(str2)
var int3 = Convert.ToInt32(str3)
is there a way to seperate the try / catch in a way that if int1 is valid (but int2 and int3 not) that int1 is still set
4 Replies
MODiX
MODiX8mo ago
The TryParse pattern is considered best practice of parsing data from a string: - a TryParse method returns true or false to inform you if it succeeded or not, so you can use it directly in a condition, - since C# 7 you can declare a variable that will be used as an out argument inline in an argument list, - it forces you to check if the out argument contains valid data afterwards, Avoid: Convert.ToInt32 — it's a bad choice for parsing an int. It exists only for backwards compatibility reasons and should be considered last resort.
return Convert.ToInt32(null); //returns 0. null should not be considered as 0 ever
return Convert.ToInt32("asdf"); //throws FormatException
return Convert.ToInt32(null); //returns 0. null should not be considered as 0 ever
return Convert.ToInt32("asdf"); //throws FormatException
(Note: Convert does contain useful conversion methods: To/FromBase64String, To/FromHexString, ToString(X value, int toBase), ToX(string? value, int fromBase)) Avoid: int.Parse — you have to use a try/catch statement to handle invalid input, which is a less clean solution.
var number = int.Parse("abc"); //throws FormatException
var number = int.Parse(""); //throws FormatException
var number = int.Parse("abc"); //throws FormatException
var number = int.Parse(""); //throws FormatException
Use int.TryParse https://docs.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-5.0#System_Int32_TryParse_System_String_System_Int32__
if (int.TryParse(someInput, out var result))
{
Console.WriteLine($"Thanks for giving me the following number: {result}!");
}
else
{
Console.WriteLine("You didn't give me a valid number :c");
}
if (int.TryParse(someInput, out var result))
{
Console.WriteLine($"Thanks for giving me the following number: {result}!");
}
else
{
Console.WriteLine("You didn't give me a valid number :c");
}
Buddy
Buddy8mo ago
Do you mean wrapping each of them in a try / catch? Not exactly sure what you mean.
Livid
Livid8mo ago
yes, like wrapping each line in try catch
Jimmacle
Jimmacle8mo ago
declare the ints outside of the try/catch and then inside the try block parse them in the order you want them to be set? try/catch blocks aren't like transactions, any code that executes before an exception is thrown still modifies the program's state if you want them entirely separate then you'd have to do individual try/catch blocks but the real answer is to use TryParse