1

I have created a custom exception class like the one below

public class FailedException : Exception { private string failedtext; public FailedException(string message) : base(message) { } public FailedException(string message) : base(message, innerException) { } public string failedtext { get {return failedtext;} set {failedtext = value;} } } 

I am able to set the property failedtext when throwing the exception, but unable to get the failedtext in my main code; the exception comes as an innerexception, I can see the property but cannot get it. Is there a way to do this?

I want to get the value of failedtext to handle the error. Thanks.

1
  • 1
    How are you throwing this exception and how are you catching it? Commented Jul 23, 2016 at 2:25

1 Answer 1

3

If your main code looks like this:

try { ThisWillThrow() } catch(Exception ex) { ex.InnerException.failedtext; //compile error on this line } 

The problem is that InnerException property is typed as Exception. You can safely cast the object to your custom type by changing the catch block to:

catch(Exception ex) { FailedException fex = ex.InnerException as FailedException; if (fex != null) { string text = fex.failedtext; } } 

Also consider using the Data property of Exception instead of this custom type:

//thrower's code Exception x = new Exception("my message"); x.Data["failedtext"] = "my failed text"; //catcher's code: catch(Exception ex) { if (ex.Data.Contains("failedtext") && ex.Data["failedtext"] is string) { string text = ex.Data["failedtext"]; } } 

Also, your property is recursively defined. Change it to this:

 public string failedtext { get; set; } 
Sign up to request clarification or add additional context in comments.

1 Comment

Regarding the last comment about the recursive property, I think OP is just showing us text code as it wouldn't even compile.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.