title: Exception handling of coroutines in Unity
body: <p>I created a script that changes the transparency of the GameObject it's attached to and I do the transparency change in a fading coroutine which needs to be cancellable (and canceled everytime we call <code>ChangeTransparency()</code> with a new value). I managed to get it working the way I want it but I want to handle the <code>OperationCanceledException</code> that is flooding my Console. I know that you <strong>cannot</strong> wrap a <code>yield return</code> statement inside a <code>try-catch</code> block.</p>
  <p><strong>What is a proper way to handle Exceptions inside Unity coroutines?</strong></p>
  <p>Here is my script:</p>
  <pre><code>using System;
  using System.Collections;
  using System.Threading;
  using UnityEngine;
  
  public class Seethrough : MonoBehaviour
  {
      private bool isTransparent = false;
      private Renderer componentRenderer;
      private CancellationTokenSource cts;
      private const string materialTransparencyProperty = &quot;_Fade&quot;;
  
  
      private void Start()
      {
          cts = new CancellationTokenSource();
  
          componentRenderer = GetComponent&lt;Renderer&gt;();
      }
  
      public void ChangeTransparency(bool transparent)
      {
          //Avoid to set the same transparency twice
          if (this.isTransparent == transparent) return;
  
          //Set the new configuration
          this.isTransparent = transparent;
  
          cts?.Cancel();
          cts = new CancellationTokenSource();
  
          if (transparent)
          {
              StartCoroutine(FadeTransparency(0.4f, 0.6f, cts.Token));
          }
          else
          {
              StartCoroutine(FadeTransparency(1f, 0.5f, cts.Token));
          }
      }
  
      private IEnumerator FadeTransparency(float targetValue, float duration, CancellationToken token)
      {
          Material[] materials = componentRenderer.materials;
          foreach (Material material in materials)
          {
              float startValue = material.GetFloat(materialTransparencyProperty);
              float time = 0;
  
              while (time &lt; duration)
              {
                  token.ThrowIfCancellationRequested();  // I would like to handle this exception somehow while still canceling the coroutine
  
                  material.SetFloat(materialTransparencyProperty, Mathf.Lerp(startValue, targetValue, time / duration));
                  time += Time.deltaTime;
                  yield return null;
              }
  
              material.SetFloat(materialTransparencyProperty, targetValue);
          }
      }
  }
  </code></pre>
  <p>My temporary solution was to check for the token's cancellation flag and break out of the while loop. While it solved this current problem, I am still in need of a way to handle these exceptions that are thrown in asynchronous methods (coroutines) in Unity.</p>