C
C#5d ago
Faker

✅ Error handling in C#

Hello guys, consider the following code:
C#
using System;

namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
Person person = new Person("john", 21, "[email protected]");
Console.WriteLine(person);

// Updating and veryfying name
person.NameVerification("Somebody123");

// Updating and verifying age
person.AgeVerification(200);

// Updating and verifying email
var emailResult = person.IsValidEmail("johngmail.com");
if (emailResult)
{
Console.WriteLine("Valid Email");
}
else
{
Console.WriteLine("Invalid Email");
}
}
}
}
C#
using System;

namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
Person person = new Person("john", 21, "[email protected]");
Console.WriteLine(person);

// Updating and veryfying name
person.NameVerification("Somebody123");

// Updating and verifying age
person.AgeVerification(200);

// Updating and verifying email
var emailResult = person.IsValidEmail("johngmail.com");
if (emailResult)
{
Console.WriteLine("Valid Email");
}
else
{
Console.WriteLine("Invalid Email");
}
}
}
}
If I try to wrap the AgeVerification in a try catch block and pass a string instead of an int, my IDE yell an error at me, like its not a runtime exception (I think we say it's a checked exception), why is that? Even with the try catch. In my class Person, I didn't include a try catch in the method doing the work though. Normally, should we also include try catch block in the Person class? Like for AgeVerification here?
43 Replies
Thinker
Thinker5d ago
trying to pass a string to a method which expects an int is a compile-time error, not a runtime one
Faker
FakerOP5d ago
ah I see I should try to take user input instead so that the compiler doesn't know what would happen ? then I can implement the try catch ?
Angius
Angius5d ago
Do you want to cause an exception?
ACiDCA7
ACiDCA75d ago
if you want to be able to pass a string you have to create a override that can accept strings
Faker
FakerOP5d ago
yeahh
Angius
Angius5d ago
int.Parse() will throw when you give it a string that is not an integer
Faker
FakerOP5d ago
yeah will try that
Thinker
Thinker5d ago
(in general you want to avoid exceptions as much as reasonably possible tho)
Faker
FakerOP5d ago
2sec yeahh, that just to test
Angius
Angius5d ago
var input = Console.ReadLine();
var number = int.Parse(input);
var input = Console.ReadLine();
var number = int.Parse(input);
is an easy way to cause exceptions Give it "98.2", give it "cat" and see the throw
Faker
FakerOP5d ago
hmm what do you mean pls yep, was going to do something similar, thanks ! by the way the proper syntax is now Try.intParse() ? I forgot the arguments it takes though
ACiDCA7
ACiDCA75d ago
in person create a second AgeVerification method just with a string parameter instead of int
Angius
Angius5d ago
Huh?
Faker
FakerOP5d ago
well Try.intParse won't give the exception I think, just return true or false
ACiDCA7
ACiDCA75d ago
you gotta do what zz wrote there anyway
Angius
Angius5d ago
There's no Try.intParse() Did you mean int.TryParse()?
Faker
FakerOP5d ago
ops my bad, yeah
Angius
Angius5d ago
If so, then yeah, this will avoid an exception and instead will return false
Faker
FakerOP5d ago
ahhh I see will just finish an exercise and will try what you guys suggested
FusedQyou
FusedQyou5d ago
Something to remember is that by convention, anything prefixed with Try gracefully attempts to parse or otherwise convert a value into what you want. It returns a boolean to indicate success. This is known as the Try-Parse pattern and you should use it when you have to validate data coming from code that is not yours: https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/exceptions-and-performance#try-parse-pattern
Exceptions and Performance - Framework Design Guidelines
Learn more about: Exceptions and Performance
FusedQyou
FusedQyou5d ago
You can/should also use it on your internal code, but you should probably wonder if this is the proper flow of your code or if you should ensure it's valid to begin with In this case, since you probably simulate data coming in from the outside, you should definitely use the Try-Parse pattern And also commenting on this, the whole point to avoid it is because there are better, faster and more performant ways of handling errors that happen due to an invalid state coming in. Exceptions are slow and bad and should not be used as a result when something that can go wrong goes wrong. They should only be used when the data coming in or the state of the code is in an unintended bad state and should be fixed. Perfect code should never throw an exception ideally. There's one exception btw, you could argue here, which is task cancellation
Thinker
Thinker5d ago
However note that exceptions are still alright to use, but only in situations where there are no reasonable alternatives, such as reaching a state which should in theory never be reached. also yeah task cancelation ig
FusedQyou
FusedQyou5d ago
That falls under reaching an unintended bad state
Thinker
Thinker5d ago
ooh right, sorry, didn't read your message properly
FusedQyou
FusedQyou5d ago
One thing that is often used in this case is Type unions. The latest .NET almost had this build in, but it was cancelled close to release if I remember correctly. I believe I used language-ext as an alternative which does the same really. You'd return a preferred result object which contains a positive or negative result inside, and you can gracefully handle from there.
GitHub
GitHub - louthy/language-ext: C# pure functional programming framew...
C# pure functional programming framework - come and get declarative! - louthy/language-ext
FusedQyou
FusedQyou5d ago
This video explains it pretty well: https://www.youtube.com/watch?v=aksjZkCbIWA
Nick Chapsas
YouTube
The New Option and Result Types of C#
Get our GitHub Actions course and get the Git course for free: https://dometrain.com/course/from-zero-to-hero-github-actions/ Subscribe to my weekly newsletter: https://nickchapsas.com Become a Patreon and get special perks: https://www.patreon.com/nickchapsas Hello, everybody. I'm Nick, and in this video, I will talk about the Result and Opti...
Thinker
Thinker5d ago
god no don't use language ext There's a time and place for result types, but everywhere in your code is not that
FusedQyou
FusedQyou5d ago
I don't mean use it everywhere It can't replace exceptions I just mean that gracefully handling issues/errors can also be done like this. It's more suited for a purpose where you have multiple returning results (i.e. user creation can result in Created, EmailExists or UsernameExists result types) I think if this is natively supported in .NET the use case would be must better fitted here. I see they actually updated the proposal a week ago so hopefully it's reconsidered for .NET 10
Unknown User
Unknown User5d ago
Message Not Public
Sign In & Join Server To View
Thinker
Thinker5d ago
And LanguageExt is kinda terrible for what it promises to do anyway
Unknown User
Unknown User5d ago
Message Not Public
Sign In & Join Server To View
FusedQyou
FusedQyou5d ago
What does asynchronous programming have to do with this?
Unknown User
Unknown User5d ago
Message Not Public
Sign In & Join Server To View
FusedQyou
FusedQyou5d ago
I don't see the problem
Unknown User
Unknown User5d ago
Message Not Public
Sign In & Join Server To View
MODiX
MODiX5d ago
If you have no further questions, please use /close to mark the forum thread as answered
Faker
FakerOP4d ago
yep solved, sorry sorry, just read this message; when we use TryParse() , I didn't understand, is there any thing specific we need to do/take into account ?
FusedQyou
FusedQyou4d ago
The TryParse pattern (not just int.TryParse in this case) is a general pattern that specifies the method gracefully attempts a conversion without raising exceptions. Instead it returns a boolean indicating success and one or more out parameters So anything prefixed with Try works like this
Faker
FakerOP4d ago
ah so we don't expect an "Exception error message" but a boolean value ?
FusedQyou
FusedQyou4d ago
Yes And I think this always applies, unless you added an additional parameter that would be wrong For example, int.Parse can also specify the numeric type since it might have trouble parsing a hexadecimal or other format. This is an enum, but if you give it a bad value that isn't part of the list it will throw But this is not part of the pattern, this is just a very bad mistake in the code This is specific to the topic, which is the value being converted. Anything around it could still throw if provided wrong int.TryParse: https://github.com/microsoft/referencesource/blob/master/mscorlib/system/int32.cs#L160 And see it calls ValidateParseStyleInteger which is this: https://github.com/microsoft/referencesource/blob/master/mscorlib/system/globalization/numberformatinfo.cs#L818 So it could throw if your enum is wrong, since an enum can be any numeric value Just a thought, unless you wrote the code wrong (since you generally just use the enum) this would not happen
Faker
FakerOP4d ago
yep I see, will need to investigate that later on, thanks !
Angius
Angius4d ago
$tryparse
MODiX
MODiX4d ago
When you don't know if a string is actually a number when handling user input, use int.TryParse (or variants, e.g. double.TryParse)
if (int.TryParse("123", out int number))
{
var total = number + 1;
Console.WriteLine(total); // output: 124
}
if (int.TryParse("123", out int number))
{
var total = number + 1;
Console.WriteLine(total); // output: 124
}
TryParse returns a bool, where true indicates successful parsing. - Avoid int.Parse if you do not know if the value parsed is definitely a number. - Avoid Convert.ToInt32 entirely, this is an older method and Parse should be preferred where you know the string can be parsed. Read more here

Did you find this page helpful?