Fluent.TryCatch is a lightweight library that adds support for fluent try...catch statements to .Net. It incorporates all the funtionality of the standard try...catch statement, but with a fluent syntax.
$ dotnet add package Fluent.TryCatchFluent.TryCatch is a lightweight library that adds support for fluent try...catch statements to .Net. It incorporates all the funtionality of the standard try...catch statement, but with a more fluent syntax.
Simplicity. Sometimes the standard try...catch statement can be verbose and difficult to read, especially for small segments of code. The fluent syntax offered by this library makes it easier to write and understand.
try clausecatch blockswhen clause for each catch blockThrowAs operator to change the type of exception thrown.ignore operator that discards non controlled exceptionsfinally blocktry...catch statementFluent.Try(() =>
// Your code here
).Catch(e =>
// Handle Exception
).Execute();
Translates to:
try
{
// Your code here
}
catch (Exception e)
{
// Handle Exception
}
try...catch statements with a when clauseFluent.Try(() =>
// Your code here
).Catch<ArgumentOutOfRangeException>(e =>
// Handle ArgumentOutOfRangeException
).Catch(e =>
// Handle OutOfMemoryException or ArgumentNullException
).When(e => e is OutOfMemoryException || e is ArgumentNullException)
.Catch(e =>
// Handle Exception
)
.Execute();
Translates to:
try
{
// Your code here
}
catch (ArgumentOutOfRangeException e)
{
// Handle ArgumentOutOfRangeException
}
catch (Exception e) when (e is OutOfMemoryException || e is ArgumentNullException)
{
// Handle OutOfMemoryException or ArgumentNullException
}
catch (Exception e)
{
// Handle Exception
}
ignore operator with a finally blockFluent.Try(() =>
// Your code here
).Ignore()
.Finally(() =>
// Your code here
)
.Execute();
Translates to:
try
{
// Your code here
}
catch (Exception e)
{
// Empty catch
}
finally
{
// Your code here
}
int result = Fluent.Try(() =>
return 1;
).Catch<ArgumentNullException>(e =>
return 2;
).Catch(e =>
// No return value -> default value is returned
).Execute<int>();
Translates to:
int result;
try
{
result = 1;
}
catch (ArgumentNullException e)
{
result = 2;
}
catch (Exception e)
{
result = default; // 0
}
Note: If a block does not return a value, the default value will be automatically returned.