Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Catching exception with `when` clause will not work as expected when using IL2CPP.

Discussion in 'Scripting' started by HailongChen, Oct 16, 2020.

  1. HailongChen

    HailongChen

    Joined:
    Aug 24, 2019
    Posts:
    3
    Here's the code which repeat the bug:

    Code (CSharp):
    1.     private void TestCatchWhen()
    2.     {
    3.         // Condition in when clause evaluates to true, everything is all right.
    4.         // Always output "CustomException: code = 0".
    5.         CatchException(0);
    6.  
    7.         // Condition in when clause evaluates to false, something is going wrong.
    8.         // When using MONO, the output is "Exception: This is custom exception!"
    9.         // When using IL2CPP, the output is "** Should not reach here **"
    10.         CatchException(1);
    11.     }
    12.  
    13.     private void CatchException(int code)
    14.     {
    15.         try
    16.         {
    17.             try
    18.             {
    19.                 throw new CustomException("This is custom exception!") { Code = code };
    20.             }
    21.             catch (CustomException ce)
    22.             when (ce.Code == 0) // This will NOT work as expected if the condition evaluates to false when using IL2CPP!
    23.             {
    24.                 Debug.LogErrorFormat("CustomException: code = {0}", ce.Code);
    25.             }
    26.             catch (Exception e)
    27.             {
    28.                 Debug.LogErrorFormat("Exception: {0}", e.Message);
    29.             }
    30.         }
    31.         catch (Exception)
    32.         {
    33.             Debug.LogError("** Should not reach here **");
    34.         }
    35.     }
    The definition of CustomException is:
    Code (CSharp):
    1. public class CustomException : Exception
    2. {
    3.     public int Code { get; set; }
    4.  
    5.     public CustomException(string message) : base(message)
    6.     { }
    7. }
    The expected behaviour of
    CatchException(1)
    is that it always outputs "Exception: This is custom exception!".
     
  2. HailongChen

    HailongChen

    Joined:
    Aug 24, 2019
    Posts:
    3
    By the way, I'm using Unity 2019.4.11f1.
    Here's the project which repeat the bug.
     

    Attached Files:

  3. EternalAmbiguity

    EternalAmbiguity

    Joined:
    Dec 27, 2014
    Posts:
    3,144
  4. HailongChen

    HailongChen

    Joined:
    Aug 24, 2019
    Posts:
    3