java - URL 读取 : works in main, 但不在构造函数中

标签 java

我正在开发一个基于Alphavantage API的软件。我为每只股票设计了一个对象,其中有一个 ArrayList 存储股票的历史价格。为此,我读取了一个 url,该 url 引导我访问 cvs 文件,我可以从中提取所需的数据。这在主函数中有效,但在构造函数中却无效。使用 public Stock(Stringticker) throws Exception 我收到一条错误消息

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

没有抛出异常我得到

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

}

最佳答案

你必须声明你的 Stock 构造函数,可能会抛出 IOException,所以在签名中添加 Exception 声明:

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

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

    public static void main(String[] args) {

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

关于java - URL 读取 : works in main, 但不在构造函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51926275/

相关文章:

java - 如何在 Java 8 中用定界符连接两个 Optional<String>

java - 是否可以将在paintComponent中创建的多个对象设置为一个完整的变量?即由矩形、直线和椭圆组成的面

java - 如何显示 arraylist 中的重复项计数

java - Spring MVC DispatcherServlet 错误

java - 使用 Google Chart API 从数据库生成图表

java - 无法将 jar 添加到 OSGi 包

java - Scala 如何将模拟对象注入(inject) ScalatraFlatSpec

java - 如何进行安全的向下转换并防止 ClassCastException

java - 如何在 Clojure 中正确导入用户定义的类

java - 使用 Jackson 将字符串转换为对象