URL读取:在主要版本中有效,但在构造函数中无效

时间:2018-08-20 07:53:32

标签: java

我正在开发基于Alphavantage API的软件。我为每个股票设计了一个对象,该对象将具有一个ArrayList,用于存储股票的历史价格。为此,我读取了一个指向cvs文件的URL,从中可以提取所需的数据。这在main函数中有效,但是在构造函数中则无效。使用public Stock(String ticker) throws Exception时出现错误消息

 error: unreported exception Exception; must be caught or declared to
 be thrown
         Stock msft = new Stock("MSFT");

没有throws Exception我得到

 error: unreported exception MalformedURLException; must be caught or
 declared to be thrown
         URL url = new URL(link);

我不太了解我的代码有什么问题。有人可以帮我吗?这是完整的源代码:

import java.net.*;
import java.io.*;
import java.util.ArrayList;
import java.lang.Math.*;

public class SmartBeta {

    public static void main(String[] args) {

        Stock msft = new Stock("MSFT");
    }
}

class Stock{
    //ArrayList to store prices
    private ArrayList<Double> prices = new ArrayList<Double>();

    //stock constructor
    //the argument takes the ticker symbol, in order to find the 
    //corresponding data
    public Stock(String ticker){
        String link = "https://www.alphavantage.co/query?function=TIME_SERIES_WEEKLY_ADJUSTED&symbol="+ticker+"&apikey=PRIVATE_KEY&datatype=csv";
        URL url = new URL(link);
        String cvsSplitBy = ",";
        URLConnection yc = url.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
        String inputLine;
        int i = 0;
        //we read the csv file returned, seperate it by commas, convert the 
        //numbers into doubles and store them in the ArrayList
        while ((inputLine = in.readLine()) != null) {
            if (i == 0) {
                ++i;
                continue;
            }
            String[] data = inputLine.split(cvsSplitBy);
            prices.add(Double.parseDouble(data[5]));
            ++i;
        }
        in.close(); 
        System.out.println(prices);   
    }

}

1 个答案:

答案 0 :(得分:2)

您必须声明您的Stock构造函数,可能会引发IOException,因此在签名中添加Exception声明:

public Stock(String ticker) throws IOException {...}

然后在您的main方法中处理此异常:

    public static void main(String[] args) {

    try {
        Stock msft = new Stock("MSFT");
    } catch (IOException e) {
        //exception - do something
        e.printStackTrace();
    }
}