Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct Use of .NET Exception

Tags:

c#

exception

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

like image 985
destructo_gold Avatar asked Dec 18 '22 01:12

destructo_gold


1 Answers

In exactly the same situation, the .NET designers at Microsoft chose to throw ArgumentException with a descriptive message. Oh, and they were pretty consistent about that.

like image 156
Ben Voigt Avatar answered Dec 24 '22 00:12

Ben Voigt