Results 1 to 5 of 5
- 06-18-2010, 05:01 PM #1
Member
- Join Date
- Mar 2010
- Posts
- 8
- Rep Power
- 0
Dealing with IndexOutOfBoundsExceptions
I'm just wondering what the best method is for dealing with IndexOutOfBoundsExceptions at the moment I use something like this:
But returning null doesn't really seem like the best solution to me, is there a better way of dealing with this.Java Code:public Person getPersonAtIndex(int index){ try{ return this.m_people.elementAt(index); }catch(IndexOutOfBoundsException e){ return null; } }
- 06-18-2010, 05:12 PM #2
Have the method throw the exception itself and pass it to where the code that gen'ed the bad index can handle it.
- 06-18-2010, 08:37 PM #3
Senior Member
- Join Date
- Feb 2010
- Location
- Ljubljana, Slovenia
- Posts
- 470
- Rep Power
- 4
Just like Norm said, this way you don't have to worry about what the returned null means, since it could be a valid value. This works just fine:
Then you catch the exception in your driver class.Java Code:public Person getPersonAtIndex(int index) throws IndexOutOfBoundsException { if(index >= m_people.size()) throw new IndexOutOfBoundsException(); return this.m_people.elementAt(index); }Ever seen a dog chase its tail? Now that's an infinite loop.
- 06-18-2010, 09:09 PM #4
This would also work.Java Code:public Person getPersonAtIndex(int index) throws IndexOutOfBoundsException { return this.m_people.elementAt(index); }
The other gives you a place to put some debug code before the exception is thrown.
- 06-19-2010, 01:33 AM #5
Similar Threads
-
Dealing with exceptions in my simple GUI app involving a process
By fawkes711 in forum AWT / SwingReplies: 2Last Post: 12-08-2009, 08:33 PM -
dealing with (zip) files
By aloula in forum Advanced JavaReplies: 4Last Post: 10-06-2009, 07:32 PM -
dealing with database in wireless mobile midlet problem!
By coldvoice05 in forum JDBCReplies: 2Last Post: 09-23-2009, 06:46 PM -
Dealing with iReport 3.0.0
By HotEvilGirl in forum New To JavaReplies: 6Last Post: 09-11-2009, 11:32 AM -
Inconsistencies dealing with null
By xcallmejudasx in forum New To JavaReplies: 3Last Post: 05-11-2009, 08:58 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks