java - 未报告的异常 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 ?
提前致谢
解决方案
据我了解,您尝试过类似
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...
}
但老实说,我想知道你为什么声明logics
为static
. 从您的其余代码中并不明显。另外,我看到你有一个非静态getLogics()
方法。所以我想说,如果真的没有理由将它声明为static
,只需将其设为非静态并在构造函数中对其进行初始化,您可以在其中尽情使用try...catch
。
推荐阅读
- python - 我认为 Librosa.effect.split 有问题?
- python - 使用python在json文件中查找元素
- c# - 无法在 64 位 ARM 机器上运行单文件可执行 dotnet 应用程序
- sql - 由于数据类型,无法查询从 Google 表格加载的 BigQuery 表
- reactjs - 我们可以将 LWC 组件集成到 REACT JS 中吗
- php - 完整日历未更新到数据库
- elasticsearch - 基于以相反顺序显示的文档索引时间来提升结果
- typescript - 自定义组件打字稿上的 ForwardRef
- java - GSON:两个类中引用的相同对象,解码后重复的实例
- terraform - 变量中的 Terraform 变量