如何获取自定义文件未找到消息

问题描述 投票:0回答:1

当我的代码运行并且用户放入无法找到的位置或输入不起作用时,系统将返回带有链接的文件未找到异常。我不知道如何获取该异常消息以输出关于如何使程序工作的用户指令,而不仅仅是说找不到文件。

  package url_request;

 import java.io.BufferedReader;
 import java.io.InputStreamReader;
 import java.net.HttpURLConnection;
 import java.net.URL;
 import java.util.Scanner;

 import org.json.JSONArray;
 import org.json.JSONObject;

  public class Test_URL_req {
static Scanner input = new Scanner(System.in);

public static void main(String[] args) {




    try {


        String Usercity = "";
        System.out.println("Which city would you like to view");
        Usercity = input.next();




    String url = "http://api.openweathermap.org/data/2.5/weather?q="+Usercity+",uk&units=metric&appid=10a285fd9251176efb6e230da704ba43";
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();




    BufferedReader in = new BufferedReader(
             new InputStreamReader(con.getInputStream()));
     String inputLine;
     StringBuffer response = new StringBuffer();
     while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
     }
     in.close();



     JSONObject myResponse = new JSONObject(response.toString());
     JSONObject main_data = myResponse.getJSONObject("main");
     JSONObject wind_data = myResponse.getJSONObject("wind");



     JSONArray weatherarray= myResponse.getJSONArray("weather");
     JSONObject weatherreport = weatherarray.getJSONObject(0);

     String main = weatherreport.getString("main");
     String description = weatherreport.getString("description");



     System.out.println("City - "+myResponse.getString("name"));
     System.out.println("Temp C - "+main_data.getDouble("temp"));
     System.out.println("Weather Conditions- "+weatherreport.getString("main"));
     System.out.println("Weather Summary- "+weatherreport.getString("description")); 
     System.out.println("Wind speed- "+wind_data.getDouble("speed"));
     System.out.println("Wind Direction- "+wind_data.getDouble("deg"));
     System.out.println("Humidity- "+main_data.getDouble("humidity"));
     System.out.println("Pressure- "+main_data.getInt("pressure"));


     } catch(Exception e ) {
        System.out.println(e);

    }




}



}

我希望它输出有关如何正确搜索而不是找不到任何建议的文件的说明

java json api http filenotfoundexception
1个回答
0
投票

您可以显式捕获文件未找到的异常

catch(FileNotFoundException exception)

然后向用户提供您想要的所需说明?

所以你在哪里捕获异常:

catch(Exception e ) {

添加这个:

catch(FileNotFoundException e){
//Instructions}
catch(Exception e ) {
System.out.println(e);}
© www.soinside.com 2019 - 2024. All rights reserved.