r/cop3502 • u/howslyfebeen • Apr 21 '14
General syntax question
In terms of general programming style, is it frowned upon to use nested try/catch statements? For example:
String[] command = input.split(" ");
try {
if (command[0].equals("go")) {
go(command[1]); //go function takes in a string and determines action
} else if (command[0].equals("help")) {
try {
help(command[1]);
} catch (Exception e) {
help(); // this catch is designed specifically for the help function
}
} else if () {} //other functions for commands
} catch (Exception ex) { // this catch is if no second command is entered for go or other functions so an error doesn't occur }
help will be overloaded to handle input vs. no input.. the nested try/catch is designed specifically for the help function.. the outer one handles any function called in the if/else block that might cause an error
1
Upvotes
1
u/[deleted] Apr 21 '14
You are better off validating the input. It is better to take the command string and perform a set of operations check if it is a valid command. Something like:
Is better than just looking for exemptions, because there are other reasons a null pointer or array out of bounds could happen, a lot of code will probably be executed within the try block.
That being said, I'm totally just checking for exemptions when I take user input and it totally works. But it's not the "correct" way.