Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please 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. If you need help to verify your account contact hello@boards.ie

Java: try-catch inside try-catch?

  • 09-11-2022 9:48pm
    #1
    Registered Users Posts: 1,938 ✭✭✭


    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,938 ✭✭✭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: 2,003 ✭✭✭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,969 ✭✭✭✭Esel


    Not your ornery onager



  • Registered Users Posts: 1,701 ✭✭✭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