✅ Error handling in C#
Hello guys, consider the following code:
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
trying to pass a string to a method which expects an int is a compile-time error, not a runtime one
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 ?
Do you want to cause an exception?
if you want to be able to pass a string you have to create a override that can accept strings
yeahh
int.Parse()
will throw when you give it a string that is not an integeryeah will try that
(in general you want to avoid exceptions as much as reasonably possible tho)
2sec
yeahh, that just to test
is an easy way to cause exceptions
Give it
"98.2"
, give it "cat"
and see the throwhmm 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
in person create a second AgeVerification method just with a string parameter instead of int
Huh?
well Try.intParse won't give the exception I think, just return true or false
you gotta do what zz wrote there anyway
There's no
Try.intParse()
Did you mean int.TryParse()
?ops my bad, yeah
If so, then yeah, this will avoid an exception and instead will return
false
ahhh I see
will just finish an exercise and will try what you guys suggested
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-patternExceptions and Performance - Framework Design Guidelines
Learn more about: Exceptions and Performance
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
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
That falls under reaching an unintended bad state
ooh right, sorry, didn't read your message properly
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
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...
god no don't use language ext
There's a time and place for result types, but everywhere in your code is not that
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 10Unknown User•5d ago
Message Not Public
Sign In & Join Server To View
And LanguageExt is kinda terrible for what it promises to do anyway
Unknown User•5d ago
Message Not Public
Sign In & Join Server To View
What does asynchronous programming have to do with this?
Unknown User•5d ago
Message Not Public
Sign In & Join Server To View
I don't see the problem
Unknown User•5d ago
Message Not Public
Sign In & Join Server To View
If you have no further questions, please use /close to mark the forum thread as answered
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 ?
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 thisah
so we don't expect an "Exception error message" but a boolean value ?
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 happenyep I see, will need to investigate that later on, thanks !
$tryparse
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
)
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