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