Click to See Complete Forum and Search --> : [HELP]Java Exceptions
RuneMan
Aug 16th, 2008, 08:34 PM
else if (splitted[0].equals("!removepoints")) {
int repoints = Integer.parseInt(splitted[3]);
victim.removePoints(repoints);
mc.dropMessage(repoints+" points removed from "+victim.getName()+"'s account");
}
I need help! . Now the problem in the above code is if the user enters a different type of value in [splitted[3]] its gonna throw up a runtime error. Now i know im supposed to catch an exception, but which exception do i catch??
oceanebelle
Aug 17th, 2008, 03:33 AM
The Exception being thrown is probably NumberFormatException
Enclose that part with a try and catch. Also you could check the stack trace what's the actual error that is being thrown.
ComputerJy
Aug 17th, 2008, 07:29 AM
I have a hunch that an ArrayIndexOutOfBoundsException is more likely to happen..
Anyway, instead of catching the exception you need to be checking the input
leinad31
Aug 17th, 2008, 10:45 AM
Avoid a one liner... check first if index 3 exists.
RuneMan
Aug 17th, 2008, 11:16 AM
else if(splitted[0].equals("!addpoints")) {
try { MapleCharacter victim = cserv.getPlayerStorage().getCharacterByName(splitted[1]);
int points = Integer.parseInt(splitted[3]);
victim.setPoints(points);
mc.dropMessage(victim.getName()+" successfully credited with "+points+" points");
} catch(IndexOutOfBoundsException smiles) {
mc.dropMessage("Syntax: !addpoints <Charname> <Amount of Points>");
} catch(NumberFormatException ioerror) {
mc.dropMessage("A number should be given o.o");
}
}
So caught two exceptions. So shouldnt it show the Message if splitted[3] doenst exist and if the points amount is a non-integer value?
ComputerJy
Aug 17th, 2008, 11:22 AM
I can think of a dozen or more exception that might be thrown, you need to check the user input instead of handling system exceptions
RuneMan
Aug 17th, 2008, 11:37 AM
you mean something like
if(splitted.length > 3 || splitted.length< 3) {
mc.dropMessage("Incorrect command syntax");
} else {
//code
}
this?
ComputerJy
Aug 17th, 2008, 11:57 AM
Yes, something like that
I don't know what you're trying to accomplish exactly. But checking user input is more effective than waiting for an Exception to be thrown
RuneMan
Aug 17th, 2008, 12:32 PM
This is a game simulator written in Java. It takes in commands inputted by the user and proccesses them. This particular code enables gamemasters to give / remove points from users...
ill try implementing that ^^
leinad31
Aug 17th, 2008, 04:16 PM
Based on variable name splitted, I'll assume you used the split method which uses a regular expression as split criteria... if so, then you can use the matches method to check user input, e.g. you can check if a split group contains only numeric digits before actually performing the split.
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.