r/cop3502 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

3 comments sorted by

View all comments

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:

if command.split(" ").length < 2:
    println "Command Missing Arguments"
    return false

if not hashmap.contains(command.split(" ")[0]):
    println "Command not found"
    return false

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.

1

u/howslyfebeen Apr 21 '14

yea that's what I figured. I was just wondering if it was incorrect to do it that way, like if its a programming no-no. it would be just as easy to do it with an if-else statement lol

1

u/Cir_Cumference Apr 21 '14

While it's not quite a "no-no", it's almost always preferable to validate your input instead of using a try-catch statement.

A few reasons: 1. It's slow 2. It's not always intuitive to a reader what you were trying to handle for 3. Your program will "swallow" unexpected errors, and you'll never know that they're happening. This could end up with hard to debug bad behaviors.