Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3670206
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 19, 20262026-05-19T02:20:10+00:00 2026-05-19T02:20:10+00:00

In my code I have often situations like this: public void MyMethod(string data) {

  • 0

In my code I have often situations like this:

public void MyMethod(string data)
{
    AnotherClass objectOfAnotherClass = GetObject(data);
    if (objectOfAnotherClass == null)
        throw new WhatExceptionType1("objectOfAnotherClass is null.");

    if (objectOfAnotherClass.SomeProperty < 0)
        throw new WhatExceptionType2("SomeProperty must not be negative.");
}

Imagine that GetObject makes use of some external libraries which are not under my control and that this library returns null if no object for data exists and considers a negative SomeProperty as a valid state and therefore doesn’t throw an exception. Further imagine that MyMethod cannot work without objectOfAnotherClass and does not make sense with a negative SomeProperty.

What are the proper exceptions for WhatExceptionType1/2 to throw in this situation?

Basically I had four options in mind:

  • 1) InvalidOperationException, because MyMethod doesn’t make sense under the conditions described above. On the other hand the guidelines (and Intellisense in VS too) say that an InvalidOperationException should be thrown if the object the method belongs to is in an invalid state. Now the object itself isn’t in an invalid state. Instead the input parameter data and some other operations based on this parameter lead to a situation where MyMethod cannot operate anymore.

  • 2) ArgumentException, because there are values for data the method can work with and other values the method can’t. But I cannot check this by inspecting data alone, I have to call other operations before I decide.

  • 3) Exception, because I don’t know which other exception type to use and because all other predefined exceptions feel too specialized and not fitting to my situation.

  • 4) MyCustomException (my own exception type derived from Exception). This seems always an option but I am worried that I have to define lots of special exception classes for many different error conditions when I start to follow this pattern.

Are there other and better options? What are the arguments in favor or against those options?

Thank you for feedback in advance!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-19T02:20:11+00:00Added an answer on May 19, 2026 at 2:20 am

    Be careful when using built-in exception types… they have very specific meanings to the .NET framework, and unless you are using it for exactly the same meaning, it’s better to roll your own (+1 to John Saunders for Serializeable).

    InvalidOperationException has the meaning:

    The exception that is thrown when a method call is invalid for the object’s current state.

    For example, if you call SqlConnection.Open(), you get an InvalidOperationException if you haven’t specified a data source. InvalidOperationExceptionisn’t appropriate for your scenario.

    ArgumentException isn’t appropriate, either. The failure to create objectOfAnotherClass may have nothing to do with bad data being passed in. Suppose it’s a filename, but GetObject() doesn’t have permissions to read the file. As the method is written, there’s no way to know why the call to GetObject() failed, and the best you can say is the object returned was null or invalid.

    Exception is just a bad idea, in general… it gives the caller absolutely no idea why the method failed to create the object. (For that matter, having only a catch (Exception ex) {..} is a bad idea, too)

    You want exceptions that clearly identify what went wrong, and that means creating your own. Try to keep them generic to avoid 1,000 custom exceptions. I suggest:

    ObjectCreateException:   // The call to GetObject() returned null<br />
    InvalidObjectException:  // The object returned by GetObject() is invalid 
                             // (because the property < 0)
    

    Thanks for the vote ~ thought I would add an example of some custom exceptions we’ve written.

    Note that you don’t really need to add any code to the methods, because the custom exceptions don’t really do anything differently than their base classes; they just represent something different. The second example does add a property to the exception, so there’s code to support it (including constructors).

    The first is a generic base for all of our exceptions; the rule “Don’t catch general Exceptions” applies (though we do it anyway… it allows us to differentiate between exceptions we generated and exceptions thrown by the framework). The second is a more specific exception that derives from Gs3Exception and serializes a custom property.

    The .NET development team decided ApplicationException had no real-world value and deprecated it, but the purist in me always liked it, so it persists in my code. Here, though, it really does add no value and only increases the depth of the inheritance heirarchy. So feel free to inherit directly from Exception instead.

    /// <summary>
    /// A general, base error for GS3 applications </summary>
    [Serializable]
    public class Gs3Exception : ApplicationException {
    
    
        /// <summary>
        /// Initializes a new instance of the <see cref="Gs3Exception"/> class </summary>
        public Gs3Exception() {}
    
    
        /// <summary>
        /// Initializes a new instance of the <see cref="Gs3Exception"/> class </summary>
        /// <param name="message">A brief, descriptive message about the error </param>
        public Gs3Exception(string message) : base(message) {}
    
    
        /// <summary>
        /// Initializes a new instance of the <see cref="Gs3Exception"/> class 
        /// when deserializing </summary>
        /// <param name="info">The object that holds the serialized object data </param>
        /// <param name="context">The contextual information about the source or
        ///  destination.</param>
        public Gs3Exception(SerializationInfo info, StreamingContext context) : base(info, context) { }
    
    
        /// <summary>
        /// Initializes a new instance of the <see cref="Gs3Exception"/> class
        /// with a message and inner exception </summary>
        /// <param name="Message">A brief, descriptive message about the error </param>
        /// <param name="exc">The exception that triggered the failure </param>
        public Gs3Exception(string Message, Exception exc) : base(Message, exc) { }
    
    
    }
    
    
    /// <summary>
    /// An object queried in an request was not found </summary>
    [Serializable]
    public class ObjectNotFoundException : Gs3Application {
    
        private string objectName = string.Empty;
    
        /// <summary>
        /// Initializes a new instance of the <see cref="ObjectNotFoundException"/> class </summary>
        public ObjectNotFoundException() {}
    
    
        /// <summary>
        /// Initializes a new instance of the <see cref="ObjectNotFoundException"/> class </summary>
        /// <param name="message">A brief, descriptive message about the error</param>
        public ObjectNotFoundException(string message) : base(message) {}
    
    
        /// <summary>
        /// Initializes a new instance of the <see cref="ObjectNotFoundException"/> class </summary>
        /// <param name="ObjectName">Name of the object not found </param>
        /// <param name="message">A brief, descriptive message about the error </param>
        public ObjectNotFoundException(string ObjectName, string message) : this(message) {
            this.ObjectName = ObjectName;
        }
    
    
        /// <summary>
        /// Initializes a new instance of the <see cref="ObjectNotFoundException"/> class.
        /// This method is used during deserialization to retrieve properties from 
        /// the serialized data. </summary>
        /// <param name="info">The object that holds the serialized object data.</param>
        /// <param name="context">The contextual information about the source or
        /// destination.</param>
        public ObjectNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) {
            if (null != info) {
                this.objectName = info.GetString("objectName");
            }
        }
    
    
        /// <summary>
        /// When serializing, sets the <see cref="T:System.Runtime.Serialization.SerializationInfo"/> 
        /// with information about the exception. </summary>
        /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds 
        /// the serialized object data about the exception being thrown.</param>
        /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that contains contextual information about the source or destination.</param>
        /// <exception cref="T:System.ArgumentNullException">
        /// The <paramref name="info"/> parameter is a null reference (Nothing in Visual Basic) </exception>
        /// <PermissionSet>
        ///     <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Read="*AllFiles*" PathDiscovery="*AllFiles*"/>
        ///     <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="SerializationFormatter"/>
        /// </PermissionSet>
        [SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.SerializationFormatter)]
        public override void GetObjectData(SerializationInfo info, StreamingContext context) {
    
            base.GetObjectData(info, context);
    
            //  'info' guaranteed to be non-null (base.GetObjectData() will throw an ArugmentNullException if it is)
            info.AddValue("objectName", this.objectName);
    
        }
    
    
        /// <summary>
        /// Gets or sets the name of the object not found </summary>
        /// <value>The name of the object </value>
        public string ObjectName {
            get { return objectName; }
            set { objectName = value; }
        }
    
    }
    

    PS: Before anyone calls me on it, the reason for a base Gs3Exception that adds no more value than the ApplicationException is the Enterprise Library Exception Handling Application Block… by having an application-level base exception, we can create general logging policies for exceptions thrown directly by our code.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have code like this: var newMsg = new Msg { Var1 = var1,
I have code like this: template <typename T, typename U> struct MyStruct { T
I have some e-commerce code that I use often that uses Linq To SQL
I have code that references a web service, and I'd like the address of
I have code similar to this filtering entries in an Array of Objects: var
Put it another way: what code have you written that cannot fail. I'm interested
We’ve found that the unit tests we’ve written for our C#/C++ code have really
Code I have: cell_val = CStr(Nz(fld.value, )) Dim iter As Long For iter =
I have code to create another row (div with inputs) on a button click.
I have code similar to the following in many places: var dbParams = db.ReadParams(memberID,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.