首页 > 解决方案 > URL 读取:在 main 中有效,但在构造函数中无效

问题描述

我正在开发一个基于 Alphavantage 的 API 的软件。我为每只股票设计了一个对象,它将有一个 ArrayList 存储股票的历史价格。为此,我阅读了一个 url,该 url 将我引导至一个 cvs 文件,我可以从中提取我需要的数据。这在 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);   
    }

}

标签: java

解决方案


您必须声明您的 Stock 构造函数,可能会抛出 IOException,因此在签名中添加异常声明:

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

推荐阅读