java - How to Handle ArrayIndexOutOfBoundsException -


i getting -1 response. exception, how handle exception can avoid integer not match array.

constants.friends[integer.parseint(custom.getfriendslist())] 

for instance if array holds 4 items.

string[] mylist = {"one","two","three","four"}; 

if getting either -1 or value greater 3, how can handle them.

arrayindexoutofboundsexception unchecked exception, meaning signals programming errors, opposed conditions outside program's control. these exceptions should prevented, rather handled.

in specific instance, should check value before passing index array, this:

int pos = integer.parseint(custom.getfriendslist()); if (pos < 0 || pos >= constants.friends.length) {     // handle error , exit or re-read pos } // accessing friends[pos] safe now: string friend = constants.friends[pos]; 

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -