SDL, which is better?

Started by
7 comments, last by stonemetal 13 years, 9 months ago
Would this:
public bool getKeyState(int key)        {            try            {                return (keys[key]);            }            catch (Exception)            {                throw new Exception("Invalid key");            }        }

be better than
public bool[] getKeyState{ get { return (keys); } }


?

Thanks in advance,
Salvenger

[Edited by - salvenger on July 5, 2010 9:16:24 PM]
Advertisement
If the definition of keys is the same in both instances, the first doesn't do what you think it does. Invalid array access doesn't throw an exception so the first version doesn't do what you think it does(it always returns a value even if key is invalid.)

edit: Assuming this is C or C++ since we are talking about SDL.
Quote:edit: Assuming this is C or C++ since we are talking about SDL.
It looks like it's C# (SDL has bindings for a number of languages).
Thank you stonemetal, and yes this is C#.

EDIT:
public bool[] getKeyState{ return (keys); }


should be this:

public bool[] getKeyState{ get { return (keys); } }


EDIT EDIT:
Also, it seems to be catching when key is smaller and greater than the array
Quote:Original post by salvenger
Thank you stonemetal, and yes this is C#.
I think stonemetal's answer assumed C or C++; since you're programming in C#, it doesn't apply in this case. (In C#, I believe an exception will in fact be thrown if the index is out of bounds - you can read more here.)
Thanks, but it still doesn't answer my question about which is better? IYO.
Quote:Original post by salvenger
Thanks, but it still doesn't answer my question about which is better? IYO.
I don't know that there's enough context to really say which is 'better', but based on what you posted, I guess I'd say the first one (if only because it's better encapsulated and is able to offer a more specific error message in case of invalid input).
Thank you for your opinion.
(:
In C# it throws an array out of bounds exception. The first version catches it and makes a generic exception out of it. If anything I would make a more specific exception not a more general one. That way latter when you actually use this code your exception handler will be able to catch specific exceptions and be able to tell with some certainty what went wrong instead of having to catch some generic exception and have to try and puzzle through what happened. A generic exception handler will catch a more specific exception so there is no reason to manually cast to a parent like this unless we are trying to implement a specific interface and need to control what is thrown.

This topic is closed to new replies.

Advertisement