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