Is it a known good practice to use a big try-catch per method in java? [closed]

For me, two try-catch blocks makes most methods too long. It obfuscates the intention if the method is doing many things.

With two try-catch blocks, it’s doing at least four things, to be precise

  • two cases for main flow (two try blocks)
  • two cases for error handling
    (catch blocks)

I would rather make short and clear methods out of each try-catch block- like

private String getHostNameFromConfigFile(String configFile, String defaultHostName) {
    try {
        BufferedReader reader = new BufferedReader(new FileReader(configFile));
        return reader.readLine();
    } catch (IOException e) {
        return defaultHostName;
    }
}
public Collection<String> readServerHostnames(File mainServerConfigFile, File  backupServerConfigFile) {
    String mainServerHostname=getHostNameFromConfigFile(mainServerConfigFile,"default- server.example.org");
    String backupServerHostName=getHostNameFromConfigFile(backupServerConfigFile,"default- server.example.ru")
    return Arrays.asList(mainServerHostname,backupServerHostName);
}

Robert C. Martin in ‘Clean Code’ takes it to next level, suggesting:

if the keyword ‘try’ exists in a function, it should be the very first word in the function and that there should be nothing after the catch/finally blocks.

I would definitely refactor the method with two separate try/catch blocks into smaller methods.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)