Search code examples
c#exceptionconstructortry-catchthrow

C# Determinig if exception initialized with a message


Is there a way when catching an exception to determine if it were constructed with a non-default message.

        try
        {
            throw new Exception(message);      // case 1
            //throw new Exception();           // case 2
        }

        catch(Exception exp)
        {
            /* what do I put here such that if the case 2 exception were
               caught it would output exp.ToString() instead of exp.Message? */

            textBox1.Text = exp.Message;  // case 1 handeling

        }

Just to clarify when Exception(message) is thrown I want it to ouptut exp.Message and when Exception() is thrown I want to output exp.ToString(). I would prefer to accomplish this without adding a custom exception. Thanks.


Solution

  • You need to check the message against a default exception

    catch (Exception e)
    {
      bool isDefaultMessage = e.Message == new Exception().Message;
    }
    

    Update

    Difference types of Exception

    catch (Exception e)
    {
      bool isDefaultMessage = false;
      try
      {
         var x = (Exception) Activator.CreateInstance(e.GetType());
         isDefaultMessage = e.Message == x.Message;
      }
      catch (Exception) {} // cannot create default exception.
    }