首页 > 解决方案 > 未报告的异常 ParseException; 必须被捕获或声明被抛出 -- JAVA 错误

问题描述

我正在 JSF 中构建一个 Java 应用程序,该应用程序向 API 发出请求,获取一个 JSON 并用 JSON 信息填充一个表......

这是代码:

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




}

在第 67 行 ->final static private ArrayList<Logic> logics = new ArrayList<Logic>(Arrays.asList(new Logic(jo.get("cif").toString())));

它在 Netbeans 中给了我这个错误:未报告的异常 ParseException;必须被抓住或宣布被扔掉。我尝试在 try catch 中包围它,但它在代码的其他部分给出了其他错误......我该怎么做才能运行 app ?

提前致谢

标签: javacompiler-errors

解决方案


据我了解,您尝试过类似

try {
    final static private  ArrayList<Logic> logics = new ArrayList<Logic>(Arrays.asList(new Logic(jo.get("cif").toString())));
} catch (Exception e) {
    e.printStackTrace();
}

问题是,该行不在方法内,您不能try...catch在那里使用。

解决此问题的一种快速方法是将初始化放在一个static块中

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...
}

但老实说,我想知道你为什么声明logicsstatic. 从您的其余代码中并不明显。另外,我看到你有一个非静态getLogics()方法。所以我想说,如果真的没有理由将它声明为static,只需将其设为非静态并在构造函数中对其进行初始化,您可以在其中尽情使用try...catch


推荐阅读