我正在做一個使用 Mojang API 從他的用戶名回傳 Minecraft 玩家的 UUID 的方法。這個方法在引數中接受一個字串(我們想知道 UUID 的玩家的用戶名)。為了使用 API 的結果,我使用 SimpleJSON 庫(將 JSON 結果決議為要回傳的字串)。
我的方法拋出 2 個檢查例外:IOExeption 和 Parseexception,因為我想要。當用戶名錯誤(所以用戶名不存在)時,API 回傳一個空的 JSON 物件,我的方法在這種情況下拋出 IOException。這是我的問題,當方法的引數中包含錯誤的用戶名時,該方法會拋出一個新的 IOExcpetion 但嘗試并捕獲該方法時,不會捕獲拋出的例外。
我的方法:
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");
}
使用有效用戶名的示例:
public static void main(String[] args) {
try {
System.out.println(getUUID("Jeb_"));
} catch (IOException | ParseException e) {
e.printStackTrace();
}
}
現在是一個用戶名錯誤的例子:
public static void main(String[] args) {
try {
System.out.println(getUUID("d"));
} catch (IOException | ParseException e) {
e.printStackTrace();
}
}
謝謝你。
uj5u.com熱心網友回復:
您是否驗證過您的例外可能會被捕獲?如果它被捕獲,代碼將列印堆疊跟蹤。但是如果沒有被捕獲,JVM 無論如何都會列印一個堆疊跟蹤。
所以拋出一些你可以驗證的訊息的例外,比如
throw new IOException("Invalid user");
并通過更詳細一點來捕獲例外:
catch (IOException | ParseException e) {
System.out.println("Could not lookup user " username ", caught " e.getClass().getName() ": " e.getMessage());
}
uj5u.com熱心網友回復:
實際上,您的例外被捕獲,您可以按如下方式檢查它:
public static void main(String[] args) {
var username = "d";
try {
System.out.println(getUUID(username));
} catch (IOException | ParseException e) {
System.out.println("User " username " not found!");
e.printStackTrace();
}
}
該程式的輸出將是:
User d not found!
java.io.IOException
at com.company.Main.getUUID(Main.java:37)
at com.company.Main.main(Main.java:17)
此輸出表示 catch 塊內的代碼已執行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/473229.html
