Results 1 to 5 of 5
- 09-11-2012, 06:16 PM #1
Member
- Join Date
- Jul 2011
- Posts
- 21
- Rep Power
- 0
Should I be using if-else? or try-catch?
I'm making a sort of notebook application. In the class "NoteBook" there is an array of size 5 which can hold at max 5 "Note" type objects. I want to have a "getNote()" function but the user must specify a valid input (a value between 0 and 4 to be precise). Should I be using a if-else to ensure this is the case or should I be using a try-catch?
Here's the code I have, which wont compile because I have to have a guaranteed return of type "Note":
/** Returns a note from the notebook */
public Note getNote(int x)
{
if(x >= 0 && x <5)
{
return this.noteBook[x];
}
else
{
System.out.println("Invalid input, please enter a number between 0 and 5");
}
}
Probably a very obvious answer but I just really dont want to develop bad habits. Thank you.
- 09-11-2012, 06:23 PM #2
Moderator
- Join Date
- Apr 2009
- Posts
- 10,438
- Rep Power
- 16
Re: Should I be using if-else? or try-catch?
It's an if/else, and you can avoid the hardcoding by using noteBook.length instead of '5'.
And if it's out of range then I would possibly consider throwing an exception.
This (to me) does not look like the place to have UI code.Please do not ask for code as refusal often offends.
- 09-11-2012, 06:31 PM #3
Re: Should I be using if-else? or try-catch?
Why do they call it rush hour when nothing moves? - Robin Williams
- 09-11-2012, 06:50 PM #4
Member
- Join Date
- Jul 2011
- Posts
- 21
- Rep Power
- 0
Re: Should I be using if-else? or try-catch?
Are you correcting me for saying "if-else" as appose to "if/else" or are you telling me to use an if/else statement?
When I have a GUI set up I wont need a user input the user will simply click which note they want to read but for now its just to test the class' functionality.
- 09-12-2012, 09:36 AM #5
Moderator
- Join Date
- Apr 2009
- Posts
- 10,438
- Rep Power
- 16
Re: Should I be using if-else? or try-catch?
I'm saying use an if/else, because that's what it is.
You know the range, so don't rely on the ArrayIndexOutOfBounds exception.
As for the UI (not GUI), doesn't matter what sort of UI itis, it doesn't belong in your logic code.
Trust me, it'll be easier to replace your command line UI with a GUI if the command line bits are already separated.Please do not ask for code as refusal often offends.
Similar Threads
-
Try and Catch's
By dougie1809 in forum New To JavaReplies: 10Last Post: 03-15-2012, 03:23 AM -
try and catch
By Bimz in forum New To JavaReplies: 1Last Post: 09-26-2011, 09:44 AM -
how to catch two exceptions in one catch()?
By arnab321 in forum New To JavaReplies: 1Last Post: 11-06-2008, 10:54 AM -
try catch...
By MarkWilson in forum New To JavaReplies: 8Last Post: 06-27-2008, 05:39 PM -
Use try and catch
By zoe in forum New To JavaReplies: 2Last Post: 07-25-2007, 07:50 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks