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 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.
- One
try
clause - Zero to multiple
catch
blocks - Optionally, a
when
clause for eachcatch
block - A special
ThrowAs
operator to change the type of exception thrown. - A special
ignore
operator that discards non controlled exceptions - Zero to one
finally
block - Returning values
Fluent.Try(() =>
// Your code here
).Catch(e =>
// Handle Exception
).Execute();
Translates to:
try
{
// Your code here
}
catch (Exception e)
{
// Handle Exception
}
Fluent.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
}
Fluent.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.