Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

Java: try-catch inside try-catch?

  • 09-11-2022 10:48PM
    #1
    Registered Users, Registered Users 2, Paid Member Posts: 3,157 ✭✭✭


    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, Registered Users 2, Paid Member Posts: 3,157 ✭✭✭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, Registered Users 2 Posts: 2,062 ✭✭✭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, Registered Users 2 Posts: 24,343 ✭✭✭✭Esel
    Not Your Ornery Onager


    Not your ornery onager



  • Registered Users, Registered Users 2, Paid Member Posts: 1,711 ✭✭✭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.

    I subscribed to keep boards.ie alive!
    boards.ie: Now Ye're Subscribing



Advertisement