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

时间:2019-02-20 16:29:53

标签: java json api http filenotfoundexception

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

  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);

    }




}



}

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

1 个答案:

答案 0 :(得分:0)

您可以明确捕获未找到的文件异常

catch(FileNotFoundException exception)

然后向用户提供所需的指令?

所以在哪里捕获异常:

catch(Exception e ) {

添加此内容:

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