0

I'm pretty new with Polly and I'm trying to understand how works, starting from the very basics.

To test the retries I tried to create a code (Print) that has 33% to generate a DivideByZeroException. When the error is generated it raise up to policy.Execute seems don't managed by Polly.

Someone can help me to adjust this code? I'm using .Net Framework 4.7.2.

using System;
using Polly;

class Program
{
    static void Main(string[] args)
    {
        var policy = Policy
                        .Handle<DivideByZeroException>()
                        .Retry();

        policy.Execute(() => Print());
        Console.ReadKey();
    }

    private static void Print()
    {
        var rand = new Random();
        int a = rand.Next(1000, 2000);
        int b = rand.Next(0, 2);
        Console.WriteLine("a = {0} - b {1}", a, b);
        int c = a / b;
        Console.WriteLine("c = {0}", c);
    }
}
Peter Csala
  • 17,736
  • 16
  • 35
  • 75
user1812102
  • 51
  • 1
  • 6
  • Can you add an example of what you’re seeing versus what you expect to see? Note that because you’re using `Random`, the exception might not actually occur. – ErikHeemskerk Oct 03 '20 at 08:28
  • Try creating the `Random` once as a single static variable, instead of creating a new `Random` each time the `Print` runs. – Theodor Zoulias Oct 03 '20 at 09:09

1 Answers1

2

If you set b = 0, instead of using Random, you'll see it is handling the exception, but it's not retrying forever - you'll see it print output twice before failing. So it means, in the case of using Random, it's sometimes setting b to 0 multiple times in a row, in which case the policy exhausts its retries, and so it throws.

You can configure the policy to increase the number of retries using Retry(n). Alternatively, you can use RetryForever().

If you don't want your calling code to throw when the retries are exhausted, you can use capture the result instead:

var result = policy.ExecuteAndCapture(() => Print());
if (result.Outcome == OutcomeType.Failure)
{
    // result.FinalException contains the exception
}
John H
  • 14,422
  • 4
  • 41
  • 74
  • Thank you for the reply...with .Retry(1) seems working...I imagined that .Retry() was like Retry(1) but seems that I was wrong. – user1812102 Oct 03 '20 at 08:36
  • @user1812102 `Retry()` is the same as `Retry(1)`. Have you set `b = 0`? If not, you're just rolling the dice with `Random` as to whether it works or not. – John H Oct 03 '20 at 08:39
  • Maybe I made confusion looking at the output aftert the error, anyway now seems clear... – user1812102 Oct 03 '20 at 08:45