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 trial

C# Wrapping Up

Shoko Ishigaki
Shoko Ishigaki
21,826 Points

When 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?

Tyler B
Tyler B
5,787 Points

Depends 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?

Shoko Ishigaki
Shoko Ishigaki
21,826 Points

I 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
Steven Parker
231,236 Points

That 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
Shoko Ishigaki
21,826 Points

Thanks 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
Steven Parker
231,236 Points

I 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
Erik Gabor
6,427 Points

Also we could do the following:

try
{
  return _items[index];
}
catch ( System.IndexOutOfRangeException e) 
{
   System.Console.WriteLine(e.Message);
   return null;
}
Steven Parker
Steven Parker
231,236 Points

Good point, just let the system throw the exception for you.