Wilson
Wilson

Reputation: 45

URL reading: works in main, but not in constructor

I am developing a software based on the API of Alphavantage. I designed an object for each stock, which will have an ArrayList storing historical prices for the stock. To do that, I read a url that leads me to a cvs file, from which I can extract the data I need. This works in the main function, however, in the constructor it does not. With public Stock(String ticker) throws Exception I get an error saying

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

Without throws Exception I get

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

I don't really understand what is wrong with my code. Could someone help me? Here is the full source code:

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

}

Upvotes: 0

Views: 101

Answers (1)

dgebert
dgebert

Reputation: 1484

You have to declare your Stock constructor, could throw an IOException, so in signature add Exception declaration:

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

and then, in your main method handle this exception:

    public static void main(String[] args) {

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

Upvotes: 2

Related Questions