try & catch

  • Thread starter Thread starter nicol
  • Start date Start date
N

nicol

Hi

Error 1 Property or indexer 'System.Exception.Message' cannot be
assigned to -- it is read only

using System;

namespace ConsoleApplication126
{
class Program
{
static void Main(string[] args)
{
string x = null;
try
{
if (x == null)
{
Exception ex = new Exception();
ex.Message = "x was null"; // ****** error**
throw ex;
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}

}

}
 
nicol said:
Error 1 Property or indexer 'System.Exception.Message' cannot be
assigned to -- it is read only
Exception ex = new Exception();
ex.Message = "x was null"; // ****** error**

You can pass the message in the constructor:

Exception ex = new Exception("x was null");
 
    You can pass the message in the constructor:

    Exception ex = new Exception("x was null");

thanks it work . . . but could not code it in another way ? ? ?
 
thanks it work . . . but could not code it in another way ? ? ?

No, some objects have readonly properties such as this. Only the .Net
developers would know the decision behind doing this for Exception.Message.
 
Family said:
No, some objects have readonly properties such as this. Only the .Net
developers would know the decision behind doing this for Exception.Message.

My guess is that it's to keep handlers in the middle of the call stack
from tampering with exceptions and then rethrowing them.
 
Error 1 Property or indexer 'System.Exception.Message' cannot be
assigned to -- it is read only

The error message explains what the problem is in plain English.

Arne
 
My guess is that it's to keep handlers in the middle of the call stack
from tampering with exceptions and then rethrowing them.

Immutable classes is in general a good thing.

Arne
 
Back
Top