C
C#7mo 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
Angius7mo ago
The Try.... pattern is preferred Not only is it more concise to write and easier to read, it's also more performant
SWEETPONY
SWEETPONYOP7mo ago
is it because the Try.... pattern doesn't throw exceptions?
Angius
Angius7mo ago
Well, yes
FusedQyou
FusedQyou7mo ago
Huh? I thought throwing exceptions for expectable behavior is not a good idea?
Angius
Angius7mo ago
That is also true
FusedQyou
FusedQyou7mo ago
Because exceptions are slow and meant for actual invalid operations
Angius
Angius7mo ago
Exceptions should be exceptional
FusedQyou
FusedQyou7mo 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
Angius7mo ago
It is the answer here, yes
SWEETPONY
SWEETPONYOP7mo ago
thanks for helping me
Want results from more Discord servers?
Add your server