Setting the message of a custom Exception without passing it to the base constructor

custom exception c#
custom exception class
set message of exception c#
c# custom exception best practice
throw custom exception message
throw a custom exception of type missingfieldvalueexception
net custom exception
c# exception message

I want to make a custom Exception in C#, but in theory I do need to do a little parsing first before I can make a human readable ExceptionMessage.

The problem is that the orginal Message can only be set by calling the base constructor of Messsage, so I can't do any parsing in advance.

I tried overring the Message property like this:

public class CustomException : Exception
{
    string _Message;

    public CustomException(dynamic json) : base("Plep")
    {
        // Some parsing to create a human readable message (simplified)
        _Message    = json.message;
    }

    public override string Message
    {
        get { return _Message; }
    }
}

The problem is that the Visual Studio debugger still shows the message that I've passed into the constructor, Plep in this case.

throw new CustomException( new { message="Show this message" } )

results in:

If I leave the base constructor empty it will show a very generic message:

An unhandled exception of type 'App.CustomException' occurred in App.exe

Question

It looks like the Exception Dialog reads some field/property that I don't have any access too. Is there any other way to set a human readable error message outside the base constructor on Exception.

Note that I'm using Visual Studio 2012.

Just put the formatting code into a static method?

public CustomException(dynamic json) : base(HumanReadable(json)) {}
private static string HumanReadable(dynamic json) {
    return whatever you need to;
}

C#: Setting custom Messages in user defined Exceptions, User defined exceptions are very common in programs and very Message property is read-only, only get is implemented and passes a The code also Overrides the Message property because many devs do not care for Constructor base class ApplicationException 's constructor which accepts a string  As you can see, to create a custom exception class, all you have to do is extend the Java Exception class, and create a simple constructor: /** * My custom exception class. */ class AlsCustomException extends Exception { public AlsCustomException (String message) { super (message); } }

Consider the Microsoft Guidelines for creating new exceptions:

  using System;
  using System.Runtime.Serialization;

  [Serializable]
  public class CustomException : Exception
  {
    //
    // For guidelines regarding the creation of new exception types, see
    //    https://msdn.microsoft.com/en-us/library/ms229064(v=vs.100).aspx
    //

    public CustomException()
    {
    }

    public CustomException(string message) : base(message)
    {
    }

    public CustomException(string message, Exception inner) : base(message, inner)
    {
    }

    protected CustomException(SerializationInfo info, StreamingContext context) : base(info, context)
    {
    }

    public static CustomException FromJson(dynamic json)
    {
      string text = ""; // parse from json here

      return new CustomException(text);
    }
  }

Note the static factory method (not part of the pattern), that you can use in your program like this:

throw CustomException.FromJson(variable);

That way you followed best practice and can parse your json inside the exception class.

How to create and throw a custom exception in Java, How do you throw a custom error message in Java? If you want to expose the constructors of Exception through Exceptions then you're going to have to define them on Exceptions and call them using base from there, since inheriting exceptions calling base are calling Exceptions, hence Exception isn't their base and therefore the constructors not accessible.

I think the problem may be with the Visual Studio debugger. I got the same exact results you got using the debugger, but when I print the message instead:

class CustomException : Exception {
    public CustomException(dynamic json)
        : base("Plep") {
            _Message = json.message;
    }

    public override string Message {
        get { return _Message; }
    }

    private string _Message;
}

class Program {
    static void Main(string[] args) {
        try {
            throw new CustomException(new { message = "Show this message" });
        } catch (Exception ex) {
            Console.WriteLine(ex.Message);
        }
    }
}

I get the expected "Show this message".

If you put a breakpoint where the Exception is caught, the debugger does show you the correct message.

Need to create a new RunTimeException for EmptyStacks, If defining a custom exception doesn't provide benefit over using a regular exception in Java, there's no need to define custom exceptions and that takes a String error message and calls the parent class constructor. message and the base class takes care of setting up the custom message, according to the message . By calling super (message), we initialize the exception's error message and the base class takes care of setting up the custom message, according to the message. Now, let's use this custom exception in our code. Since we're defining a method that can throw an exception in the service layer, we'll mark it with the throws keyword.

I like to use this here. It is easy and does not need the static function:

public class MyException : Exception
{
    public MyException () : base("This is my Custom Exception Message")
    {
    }
}

How to Make Custom Exceptions in Java, which base-class constructor should be called when creating instances of the derived class. I found one possible solution in the post Custom Exception message by Corey_B. Update for "how do I pass arguments from my custom constructor to the base Save error: Object has no superclass for super invocation. Implementing a Custom Exception. Creating a custom checked exception is simple. You already saw multiple parts of it when I explained the 4 best practices for implementing custom exceptions. When you implement a checked exception, you need to extend the class Exception. That’s the only thing you need to do to create a custom exception class.

What's wrong with something like this.

    public class FolderNotEmptyException : Exception
{

    public FolderNotEmptyException(string Path) : base($"Directory is not empty. '{Path}'.")
    { }

    public FolderNotEmptyException(string Path, Exception InnerException) : base($"Directory is not empty. '{Path}'.", InnerException)
    { }

}

I just use a string and include parameters. Simple solution.

Custom Exception with a constructor that takes parameters , Learn 4 best practices for custom exceptions in Java. but I have seen way too many custom exceptions without any Javadoc. You can use this code to retrieve localized error messages and to link to our online documentation. provide a constructor method that sets the causing exception and provide a  I want to define a custom exception that has two special properties: Field and FieldValue, and I want the message to be built from those two values in the exception constructor. Unfortunately the Message is read only. This is what I have, but it still requires the message to be passed.

Implement Custom Exceptions in Java: Why, When and How, You can use custom exceptions to set your own HelpLink and Source ApplicationException class, and your class must call the base constructor for that class. ApplicationException class—and not the System . The string passed to the constructor in the example sets the Message property of the CustomException object  In my little old opinion, the best way to do it is inherit from Exception (or some other framework-supplied exception class as appropriate), then put your message string in a call to the base constructor which takes Message as a parameter, like so:

Mastering Visual C# .NET, Creating a custom exception isn't a hard thing to do, but I'm opposed to string message, Exception innerException ) : base( message,  Programs can throw a predefined exception class in the System namespace (except where previously noted), or create their own exception classes by deriving from Exception. The derived classes should define at least four constructors: one parameterless constructor, one that sets the message property, and one that sets both the Message and

Custom Exceptions Without Constructor Tedium, Message property in order to configure a custom error message and supplied two as we could simply pass the incoming message to our parent's constructor as Don't be surprised if most (if not all) of your custom exception classes follow  Base implementation, without custom properties. SerializableExceptionWithoutCustomProperties.cs: namespace SerializableExceptions { using System; using System.Runtime

Comments
  • Your code worked just fine for me. and it sould work.
  • It compiles, but if you throw an error it will show the underlying Message ("Plep"), instead of "Show this message". Please take a look at the extra example that I've added.
  • I think the ideal solution is not available. I went to a similar problem when I parsed the wholoe Exception classes to JSON. Custom properties are lost in the process. Can you describe a scenario? Perhaps we can help with some workaround.
  • I tried to throw the exception and I had the custom message that I put and not Pllep
  • Houssem, what IDE are you using? Are you looking at the same debugger dialog?
  • Perfect! Wasn't even aware that you could actually call a static method inside the arguments section of the base constructor!
  • Ah.. have to wait 19 hours before I can award you the bounty. Pretty cool that setting a bounty actually does work though ;)
  • This would work.. but in a way you are still working around the standards . I've never thrown an Exception by invoking a static method - the default .NET exceptions also don't have a static method to invoke them. I rather won't do this, because it is not very discoverable for other programmers.
  • Both links in the comment are broken. New link: Design Guidelines for Exceptions
  • I know, but the problem is indeed about the dialog that the Visual Studio debugger showed (see screenshot). Just got tired (and thought it was pretty ugly) to constantly look at the internal Exception or other ways to view the original message.