java - Java - 无法处理 IOException;必须宣布被抓住或被扔掉
问题描述
请参阅下面的代码示例错误消息:
错误:(79, 22) java: 未报告的异常 java.io.IOException; 必须被抓住或宣布被扔掉
为什么我会得到这个?我该如何解决?
public AnimalStats() throws IOException{
simulator = new Simulator();
try{
fos = new FileOutputStream("AnimalStats.csv",true);
pw = new PrintWriter(fos);
}
catch(IOException e) {
System.out.println("Error has been caught!");
e.printStackTrace();
}
}
解决方案
当您将 throws Exception 添加到方法签名时,这要求在调用方法的点“上游”处理异常。
像这样的东西:
try{
AnimalStats();
}catch(IOException ex){
// DO SOMETHING
}
但是,如果您在这一点上让签名保持沉默,您可以使用您的 try/catch 块在方法内处理异常,就像您所做的那样。但为此,您需要从方法签名中删除 throws。像这样:
public AnimalStats(){
simulator = new Simulator();
try{
fos = new FileOutputStream("AnimalStats.csv",true);
pw = new PrintWriter(fos);
}
catch(IOException e) {
System.out.println("Error has been caught!");
e.printStackTrace();
}
}
您可以使用任何一种方法。
推荐阅读
- c++ - OPENCL 警告:不兼容的指针类型将 'float __global[16]' 传递给 '__global float4 * 类型的参数
- kotlin - 等价于 if(root == null) return root; 在科特林
- python - 循环遍历子小部件并将小部件值(条目和复选按钮)存储在列表中
- python - Whatsapp 使用 Python 聊天分析器,下一步是什么?
- awk - 删除换行符,同时保持换行符后跟另一个换行符
- vba - 导出 PowerPoint 幻灯片
- linux - 在linux中为.net Core(Docker)编写txt文件
- sql-server - 我怎样才能有 CTE 的身份列
- python - 当试图用日期对浮点数绘制时间序列数据时,我在 xaxis 中收到数字而不是日期
- mysql - 在标记上拆分字符串并在拆分词上聚合