Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on [email protected] for help. Thanks :)
Hello All, This is just a friendly reminder to read the Forum Charter where you wish to post before posting in it. :)
Hi all, The AutoSave Draft feature is now disabled across the site. The decision to disable the feature was made via a poll last year. The delay in putting it in place was due to a bug/update issue. This should serve as a reminder to manually save your drafts if you wish to keep them. Thanks, The Boards Team.
Hello all! This is just a quick reminder to ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere.

Java: try-catch inside try-catch?

  • 09-11-2022 10:48pm
    #1
    Registered Users Posts: 1,164 ✭✭✭ Glaceon


    First of all, I'm not a pro by any means so my code is probably terrible, but it's a hobby project just for fun.

    I'm trying to parse an M3U playlist file to extract its contents. Currently, if the file is UTF-8, it loads fine. But if it's ASCII, a MalformedInputException is thrown. So I came up with the idea of catching the MalformedInputException and retrying with ISO-8859-1. The code sample is below and it works fine, but I think it looks a bit messy having a try-catch inside another. Is there a better way of doing this? If I only use ISO-8859-1, the formatting of international characters is garbled of course, so it's not something I'd exclusively use.

    List<String> pls;
    try {
        pls = Files.readAllLines(fd, StandardCharsets.UTF_8);
    }
    catch (MalformedInputException mie){
        // Retry using ISO-8859-1
        try {
            pls = Files.readAllLines(fd, StandardCharsets.ISO_8859_1);
        }
        catch (IOException ioe) {
            // File is unreadable, so stop
            System.err.println(ioe);
            return false;
        }
    }
    catch (IOException ex) {
        // File is unreadable, so stop
        System.err.println(ex);
        return false;
    }
    


Comments

  • Registered Users Posts: 1,164 ✭✭✭ Glaceon


    Never mind, I'm going about this in completely the wrong way. Turned out the source files I had actually had an invalid character in them. No point in trying to read it because "garbage in, garbage out". I'll stick with the original code.



  • Registered Users Posts: 1,902 ✭✭✭ Colonel Panic


    For what it’s worth, using exceptions to drive control flow is considered “bad”, but sometimes Java doesn’t give you a better option.



  • Registered Users Posts: 21,559 ✭✭✭✭ Esel


    Not your ornery onager



  • Registered Users Posts: 1,675 ✭✭✭ JoyPad


    I would recommend writing a function that attempts to read the file with a given Charset. I would also use Optional for the returned value, to avoid using exceptions for flow control. Then, you can combine the Optional values until there is a match.

    public class FileReader {
      protected static Optional<List<String>> readFile(Path file, Charset charset) {
        try {
          return Optional.of(Files.readAllLines(file, charset));
        } catch (IOException e) {
          return Optional.empty();
        }
      }
    
      public static Optional<List<String>> readFile(Path file) {
        return readFile(file, StandardCharsets.UTF_16)
                .or(() -> readFile(file, StandardCharsets.ISO_8859_1))
                .or(() -> readFile(file, StandardCharsets.UTF-8));
      }
    }
    
    Optional<List<Files>> result = FileReader.readFile(path);
    if (result.isPresent()) {
      List<String> files = result.get();
    } else {
      System.err.println("None of the charsets worked.");
    }
    

    NOTE: although Optional was added in Java8, the .or method was added in Java9.



Advertisement