Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialShoko Ishigaki
21,826 PointsWhen to throw an exception?
In our program, we throw exception when trying to create an instance of MediaType object with empty title and when encountering unexpected media subtype.
Is it ok to throw an exception when handling bad array index as well?
Shoko Ishigaki
21,826 PointsI mean like this.
if (index < _items.Length)
{
return _items[index];
}
else
{
throw new System.Exception("Index out of bounds");
}
and catch this in the main method.
2 Answers
Steven Parker
231,236 PointsThat should work just fine when combined with a "try...catch".
Also, you can make your code more compact when an "if" causes either a "return" or a "throw" because you don't need an "else":
if (index < _items.Length)
return _items[index];
throw new System.Exception("Index out of bounds");
Shoko Ishigaki
21,826 PointsThanks for your response. Is it common practice to make code compact? I feel like if ... else is easier to understand. I know this might come down to personal preference, but want to get some opinion.
Steven Parker
231,236 PointsI agree that readability is a more important "best practice" than making the code compact. Many times they go together, but when it is an "either/or" choice, I think you're right to go with readability.
Erik Gabor
6,427 PointsAlso we could do the following:
try
{
return _items[index];
}
catch ( System.IndexOutOfRangeException e)
{
System.Console.WriteLine(e.Message);
return null;
}
Steven Parker
231,236 PointsGood point, just let the system throw the exception for you.
Tyler B
5,787 PointsTyler B
5,787 PointsDepends on what you mean by "throw an exception" do you mean throw one up from a method or are you saying throw one out to the user?