C
C#8mo ago
SWEETPONY

✅ is it okay to use try/catch for logic behavior?

for example here, what is better and why
private string GetHost(string endpoint)
{
try
{
var myUri = new Uri(endpoint as string);
return myUri.Host;
}
catch
{
return endpoint;
}
}
private string GetHost(string endpoint)
{
try
{
var myUri = new Uri(endpoint as string);
return myUri.Host;
}
catch
{
return endpoint;
}
}
private string GetHost(string endpoint)
{
return Uri.TryCreate(endpoint, UriKind.Absolute, out var validUri)
? validUri.Host
: endpoint;
}
private string GetHost(string endpoint)
{
return Uri.TryCreate(endpoint, UriKind.Absolute, out var validUri)
? validUri.Host
: endpoint;
}
10 Replies
Angius
Angius8mo ago
The Try.... pattern is preferred Not only is it more concise to write and easier to read, it's also more performant
SWEETPONY
SWEETPONYOP8mo ago
is it because the Try.... pattern doesn't throw exceptions?
Angius
Angius8mo ago
Well, yes
FusedQyou
FusedQyou8mo ago
Huh? I thought throwing exceptions for expectable behavior is not a good idea?
Angius
Angius8mo ago
That is also true
FusedQyou
FusedQyou8mo ago
Because exceptions are slow and meant for actual invalid operations
Angius
Angius8mo ago
Exceptions should be exceptional
FusedQyou
FusedQyou8mo ago
Then why would Uri.TryCreate not be the answer here? I thought you should always try to use the proper methods to filter out possible wrong inputs
Angius
Angius8mo ago
It is the answer here, yes
SWEETPONY
SWEETPONYOP8mo ago
thanks for helping me
Want results from more Discord servers?
Add your server