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 711601
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T04:45:14+00:00 2026-05-14T04:45:14+00:00

What is the correct exception to throw in the following instance? If, for example,

  • 0

What is the correct exception to throw in the following instance?

If, for example, I have a class: Album with a collection of Songs:

List<Song>

And a method within Album to add a Song:

public void AddSong(Song song)
{
    songs.Add(song);
}

Should I throw an exception if a user attempts to add a song that already exists? If so, what type of exception?

I have heard the phrase: “Only use exceptions in exceptional circumstances”, but I want to tell the client implementing Album exactly what has gone wrong (not just return a Boolean value).

  • 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-14T04:45:14+00:00Added an answer on May 14, 2026 at 4:45 am

    If your use case implies that items in the collection should be unique, then you should use a datastructure that enforces that.

    By doing that, you not only avoid having to write a O(N) lookup method to check for duplicates, but you can also bubble up the pre-existing duplicate key exception that a collection of this sort would throw.

    However, .NET does not have a distinct collection that preserves sort order, though it is very easy to extend List to support this.

    The approach I used below sacrifices memory footprint for speed, by storing the unique values in a second HashSet. If memory size was more important, you’d just have to do a O(N) check on each Add operation. Because methods are not virtual (for some reason) in List, I resulted to hiding the base methods using the new keyword.

    Note that this is just an example, and is not thread safe, and should probably not be used in a real production application.

        public class UniqueList<T> : List<T>
        {
            private HashSet<T> _internalHash = new HashSet<T>();
    
            public UniqueList() : base() { }
            public UniqueList(IEnumerable<T> collection) : base(collection) { }
            public UniqueList(int capacity) : base(capacity) { }
    
            public new void Add(T item)
            {
                if (!_internalHash.Add(item))
                    throw new ArgumentException("Item already exists in UniqueList");
    
                base.Add(item);
            }
    
            public new void AddRange(IEnumerable<T> collection)
            {
                foreach (T t in collection)
                {
                   this.Add(t);
                }
            }
    
            public new bool Remove(T item)
            {
                _internalHash.Remove(item);
                return base.Remove(item);               
            }
    
            public new int RemoveAll(Predicate<T> match)
            {
                int removedElems = 0;
    
                foreach (T item in this)
                {
                    if (match(item))
                    {
                        this.Remove(item);
                        removedElems++;
                    }
                }
    
                return removedElems;
            }
    
            public new void RemoveAt(int index)
            {                
               this.Remove(this[index]);             
            }
    
            public new void RemoveRange(int index, int count)
            {
                for (int i = index; i < count; i++)
                {
                    this.Remove(this[i]);
                }
            }
        }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Let's assume we have a class Student with the following constructor: /** Initializes a
I have the following class in C# which creates an object from a propriatery
I have a base class with the following (trimmed for brevity) declaration: public abstract
The following code public class GenericsTest2 { public static void main(String[] args) throws Exception
Take the following function for example: private function connect($method, $target = $this->_config->db()) { try
Overriding Methods in java have the following features : 1> The Overrinding method should
I'm writing my Exception Handler from Spring MVC controller and I have the following
I have a custom exception class: public class MyException: Exception { public MyException(MyExceptionEnum myError)
I'm trying to figure out what the correct form of exceptions to throw would
Referring to What is the correct way to make a custom .NET Exception serializable?

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.