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