try & catch

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);
}
}

}

}
 
A

Alberto Poblacion

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");
 
N

nicol

    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 ? ? ?
 
F

Family Tree Mike

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.
 
H

Harlan Messinger

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.
 
A

Arne Vajhøj

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
 
A

Arne Vajhøj

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top