我正在开发一个基于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/