Reputation: 113
I am building a Java app in JSF that makes a request to an API gets a JSON and fills a table with the JSON info...
This is the code:
@ManagedBean(name = "logic", eager = true)
@SessionScoped
public class Logic {
static JSONObject jsonObject = null;
static JSONObject jo = null;
static JSONArray cat = null;
public void connect() {
StringBuilder sb = new StringBuilder();
try {
URL url = new URL("xxx");
URLConnection yc = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine;
while((inputLine = in.readLine())!= null){
System.out.println(inputLine);
sb.append(inputLine+"\n");
in.close();
}
}catch(Exception e) {System.out.println(e);}
try {
JSONParser parser = new JSONParser();
jsonObject = (JSONObject) parser.parse(sb.toString());
cat = (JSONArray) jsonObject.get("mesaje");
jo = (JSONObject) cat.get(0);
jo.get("cif");
System.out.println(jo.get("cif"));
}catch(Exception e){System.out.println(e);}
}
private String cif;
final static private ArrayList<Logic> logics = new ArrayList<Logic>(Arrays.asList(new Logic(jo.get("cif").toString())));
public ArrayList<Logic> getLogics() {
return logics;
}
public Logic() {
}
public Logic(String cif) throws ParseException {
this.cif = cif;
connect();
}
public String getCif() {
return cif;
}
public void setCif(String cif) {
this.cif = cif;
}
}
On line 67 -> final static private ArrayList<Logic> logics = new ArrayList<Logic>(Arrays.asList(new Logic(jo.get("cif").toString())));
it gives me this error in Netbeans: unreported exception ParseException; must be caught or declared to be thrown. I tried surrounding it in try catch but it gives other errors in other parts of code...what can I do so I can run app ?
Thanks in advance
Upvotes: 0
Views: 1397
Reputation: 27119
From what I understand, you tried something like
try {
final static private ArrayList<Logic> logics = new ArrayList<Logic>(Arrays.asList(new Logic(jo.get("cif").toString())));
} catch (Exception e) {
e.printStackTrace();
}
The problem is, that line is not inside a method, and you can't use try...catch
there.
A quick way to solve this is to put that initialization in a static
block
public class Logic {
final static private ArrayList<Logic> logics;
static {
try {
logics = new ArrayList<Logic>(Arrays.asList(new Logic(jo.get("cif").toString())));
} catch (Exception e) {
e.printStackTrace();
}
}
// rest of your class...
}
But honestly I have to wonder why you declared logics
as static
. It's not apparent from the rest of your code. Also, I see you have a non-static getLogics()
method. So I'd say, if there's really no reason to declare it as static
, just make it non-static and initialize it in the constructor, where you can use try...catch
to your heart's content.
Upvotes: 1