javaexceptiontry-catchthrowthrows

Throw Exception in method who throws this Excpetion


I am doing a method who return an UUID of a Minecraft player from his username using the Mojang API. This method takes a String in parameter (the username of the player who we want to know the UUID). To use the resultat of the API, I use the SimpleJSON library (to parse the JSON result into a String to return).

My method throws 2 checked exceptions : the IOExeption and the Parseexception, cause I want. When a wrong username (so an username who doesn't exist) the API return a empty JSON object and my method throws an IOException in this case. And this is my problem, when a wrong username is in paramter of the method, the method throw a new IOExcpetion but with a try and catch for the method, the throwing exception isn't catched.

My method :

public static String getUUID(String name) throws IOException, ParseException {
        URL url = new URL("https://api.mojang.com/users/profiles/minecraft/" + name);
        URLConnection uc = url.openConnection();
        BufferedReader bf = new BufferedReader(new InputStreamReader(uc.getInputStream()));
        StringBuilder response = new StringBuilder();
        String inputLine;
        while ((inputLine = bf.readLine()) != null) {
            response.append(inputLine);
        }
        bf.close();

        if (response.toString().isEmpty()) {
            throw new IOException();
        }
        JSONParser parser = new JSONParser();
        Object object = parser.parse(response.toString());
        JSONObject jo = (JSONObject) object;
        String str = (String) jo.get("id");
        return str.replaceAll("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5");
    }

An example of using a valid username :

public static void main(String[] args) {
        try {
            System.out.println(getUUID("Jeb_"));
        } catch (IOException | ParseException e) {
            e.printStackTrace();
        }
    }

And now an example with a wrong username:

public static void main(String[] args) {
        try {
            System.out.println(getUUID("d"));
        } catch (IOException | ParseException e) {
            e.printStackTrace();
        }
    }

Thank you.


Solution

  • Have you verified that your exception might get caught? If it is caught, the code prints a stack trace. But if it is not caught, the JVM will print a stack trace anyway.

    So throw the exception with some message you can verify, like

    throw new IOException("Invalid user");
    

    and catch the exception by being a bit more verbose:

    catch (IOException | ParseException e) {
        System.out.println("Could not lookup user "+username+", caught "+e.getClass().getName()+": "+e.getMessage());
    }