<commit_before># NiceTry
A functional wrapper type for the classic try/catch statement, inspired by its counterpart in the Scala programming language (http://www.scala-lang.org/).

Also available on NuGet (http://www.nuget.org/packages/NiceTry/).

Licensed under the Apache License 2.0 (http://www.apache.org/licenses/LICENSE-2.0.html).

## Example
Reading the content specified by a url as string and printing it to the console. If the user specifies an invalid url, a fallback url will be used.
If an error occurs anywhere during the process, the error message will be printed to the console.

```csharp
Try.To(() => new Uri(Console.ReadLine()))
   .OrElse(new Success<Uri>(FallbackUrl))
   .Map(url => {
   			using (var webClient = new WebClient()) {
   					return webClient.DownloadString(url);
            }
    })
    .Match(
    	content => Console.WriteLine("Success: {0}", content),
        error => Console.WriteLine("Failure: {0}", error.Message));
```

## Retry
A buffed `Try` that retries the given work for up to the amount of given times:

```csharp
Retry.To(() => new Uri(Console.ReadLine()), 3)
   .OrElse(new Success<Uri>(FallbackUrl))
   .Map(url => {
   			using (var webClient = new WebClient()) {
   					return webClient.DownloadString(url);
            }
    })
    .Match(
    	content => Console.WriteLine("Success: {0}", content),
        error => Console.WriteLine("Failure: {0}", error.Message));
```

The above code sample would try reading a url from the command line up to 4 times (the original try and up to 3 retries). It returns a `Success` if the user specifies a valid url before all retries are used up. If the user does not specify a valid url the fourth time, the `Retry` will fail.

------

## Basics
`Try` is a wrapper around a simple try/catch statement. It tries to execute the given `Action` or `Func` and returns a `Success` if no exception was thrown and a `Failure` containing the encountered exception otherwise.

```csharp
var result = Try.To(() => 2 + 4);
```

The above example would evaluate the anonymous function `() => 2 + 4` and, since no exception will be thrown, return a `Success<int>` and store it in the variable `result`. The result of the calculation is stored inside the `Success` and can be accessed using the `Value` property:

```csharp
var six = result.Value;
```

To find out if `result` represents a `Success` or `Failure` it provides two boolean properties: `IsSuccess` and `IsFailure`. To be safe, you can either check those properties first or use the corresponding extension:

```csharp
result.WhenSuccess(i => _six = i);
```

If the above example would have thrown an exception, it could be accessed by the `Error` property or the `WhenFailure` extension:

```csharp
var error = result.Error;

// or

result.WhenFailure(e => _error = e);
```

## Recommended usage
Every method that could throw an exception should return either an `ITry` or an `ITry<T>` instead of `void` or the result directly. That way, eventual exceptions can be handled by applying combinators and extensions to the return value and exception handling can be managed hassle free.

So instead of this:

```csharp
private void DoSomethingRisky(string a) { //... };
private int CalculateSomethingRisky(int a, int b) { //... };
```

write this:

```csharp
private ITry DoSomethingRisky(string a) { //... };
private ITry<int> CalculateSomethingRisky(int a, int b) { //... };
```

Using an `ITry` or an `ITry<T>` as return value states the risky nature of the method much clearer than a XML doc with an `<exception>` element.

## Extensions and Combinators
Since `Success` and `Failure` are simple data structures, a couple of extension methods are provided that make working with both types easier.

### Extensions
An extension is either void or returns something different than a `Success` or `Failure`. Extensions can be used to execute actions with side effect.

#### WhenComplete<commit_msg>Published with http://benweet.github.io/stackedit/<commit_after># NiceTry
A functional wrapper type for the classic try/catch statement, inspired by its counterpart in the Scala programming language (http://www.scala-lang.org/).

Also available on NuGet (http://www.nuget.org/packages/NiceTry/).

Licensed under the Apache License 2.0 (http://www.apache.org/licenses/LICENSE-2.0.html).

## Example
Reading the content specified by a url as string and printing it to the console. If the user specifies an invalid url, a fallback url will be used.
If an error occurs anywhere during the process, the error message will be printed to the console.

```csharp
Try.To(() => new Uri(Console.ReadLine()))
   .OrElse(new Success<Uri>(FallbackUrl))
   .Map(url => {
   			using (var webClient = new WebClient()) {
   					return webClient.DownloadString(url);
            }
    })
    .Match(
    	content => Console.WriteLine("Success: {0}", content),
        error => Console.WriteLine("Failure: {0}", error.Message));
```

## Retry
A buffed `Try` that retries the given work for up to the amount of given times:

```csharp
Retry.To(() => new Uri(Console.ReadLine()), 3)
   .OrElse(new Success<Uri>(FallbackUrl))
   .Map(url => {
   			using (var webClient = new WebClient()) {
   					return webClient.DownloadString(url);
            }
    })
    .Match(
    	content => Console.WriteLine("Success: {0}", content),
        error => Console.WriteLine("Failure: {0}", error.Message));
```

The above code sample would try reading a url from the command line up to 4 times (the original try and up to 3 retries). It returns a `Success` if the user specifies a valid url before all retries are used up. If the user does not specify a valid url the fourth time, the `Retry` will fail.

------

## Basics
`Try` is a wrapper around a simple try/catch statement. It tries to execute the given `Action` or `Func` and returns a `Success` if no exception was thrown and a `Failure` containing the encountered exception otherwise.

```csharp
var result = Try.To(() => 2 + 4);
```

The above example would evaluate the anonymous function `() => 2 + 4` and, since no exception will be thrown, return a `Success<int>` and store it in the variable `result`. The result of the calculation is stored inside the `Success` and can be accessed using the `Value` property:

```csharp
var six = result.Value;
```

To find out if `result` represents a `Success` or `Failure` it provides two boolean properties: `IsSuccess` and `IsFailure`. To be safe, you can either check those properties first or use the corresponding extension:

```csharp
result.WhenSuccess(i => _six = i);
```

If the above example would have thrown an exception, it could be accessed by the `Error` property or the `WhenFailure` extension:

```csharp
var error = result.Error;

// or

result.WhenFailure(e => _error = e);
```

## Recommended usage
Every method that could throw an exception should return either an `ITry` or an `ITry<T>` instead of `void` or the result directly. That way, eventual exceptions can be handled by applying combinators and extensions to the return value and exception handling can be managed hassle free.

So instead of this:

```csharp
private void DoSomethingRisky(string a) { //... };
private int CalculateSomethingRisky(int a, int b) { //... };
```

write this:

```csharp
private ITry DoSomethingRisky(string a) { //... };
private ITry<int> CalculateSomethingRisky(int a, int b) { //... };
```

Using an `ITry` or an `ITry<T>` as return value states the risky nature of the method much clearer than a XML doc with an `<exception>` element.

## Extensions and Combinators
Since `Success` and `Failure` are simple data structures, a couple of extension methods are provided that make working with both types easier.

### Extensions
An extension is either void or returns something different than a `Success` or `Failure`. Extensions can be used to execute actions with side effect. Extensions **do not** catch exceptions. You have to deal with those yourself.

#### WhenComplete
{'fraction_non_alphanumeric': 0.10846991117227574, 'fraction_numerical': 0.003753284123608157, 'mean_word_length': 3.9437229437229435, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 41, 'https://': 0, 'lorem ipsum': 0, 'www.': 6, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1709057', 'n_tokens_mistral': 2292, 'n_tokens_neox': 2160, 'n_words': 1035}