java - 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);
}
}
解决方案
您必须声明您的 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();
}
}
推荐阅读
- r - R:使用 DF 上的行操作有效地计算与平均值的偏差(不使用 For 循环)
- mysql - MySQL函数找到某个字符的出现并返回一个整数?
- javascript - Kotlin/JS 未捕获的引用错误导致的意外行为
- p5.js - 点击其他任何地方隐藏js p5
- uwp - UWP/Visual Studio 2019:在哪里可以看到组件属性的计算值和值源?
- c# - C# HttpWebRequest - 停止等待响应
- python - 为什么当我执行 element.text 时此文本字段不显示?
- c# - ComboBoxItem 中的复选框绑定到 Class 中的布尔值。如何从每个项目中获取每个布尔值?
- python - 是否可以检测函数中声明的局部变量的名称和类型?
- emacs - Doom Emacs lsp-ui 动作热键