【问题标题】:Throw statement reports IOException not handled [duplicate]Throw 语句报告 IOException 未处理 [重复]
【发布时间】:2021-05-31 15:11:46
【问题描述】:
class simpleShell{
    Process sh;
    simpleShell(String shell)  {
        try {
            sh = Runtime.getRuntime().exec(shell);
        }catch (Exception e){
            throw e;
        }
    }

}
class Main{
public satic void main(String args[]){

try {
    simpleShell ss = new simpleShell("sh");
}catch{
    //do something
}

我正在尝试为应用程序创建一个 shell 类。但是 IDE 不断报告“IOException”未处理并建议我使用 throws。我想在调用函数时处理异常而不忽略它们。我虽然构造函数不能抛出,但有些人说不然。我什至尝试做一个单独的方法来创建进程并抛出异常并尝试抛出其他异常。但同样的报告。

报告在 throw 语句中。

【问题讨论】:

  • 您正在从该方法中抛出一个异常,但它并没有这样声明它。您需要在签名中添加throws Exception在方法中使用throw e
  • First:Java 类名以大写字母开头。第二:构造函数当然可以抛出异常。
  • 这段sn-p代码与构造函数抛出异常有什么关系?您确定此代码代表您所询问的内容吗?
  • 抱歉问题质量不佳。但它与发布的内容不同。你能看到编辑并再次帮助我吗?

标签: java exception throw


【解决方案1】:

调用具有throws IOException(或任何其他类型的异常)的方法的方法(或构造函数)需要要么捕获异常,要么声明它也抛出它。

当一个方法声明它抛出异常时,它的调用者也必须捕获或声明异常。

所以你可以:

void create(String shell){
        try {
            sh = Runtime.getRuntime().exec(shell);
        }catch (IOException e){
            // handle the exception in some way
        }
}

void create(String shell) throws IOException {
   sh = Runtime.getRuntime().exec(shell);
}

如果你想捕获异常,做一些事情,然后重新抛出它,你需要声明你的方法抛出异常:

void create(String shell) throws IOException {
        try {
            sh = Runtime.getRuntime().exec(shell);
        }catch (IOException e){
            // handle the exception in some way
            // then rethrow it
            throw e;
        }
}

【讨论】:

  • 也许我的问题不清楚。我想捕获可以的异常。但我想将捕获的异常抛出给调用者函数。每当我尝试使用它时,ide 报告 IOException 未处理
  • @RiyadhKabir 我添加了一个显示该行为的示例
  • 但是不会抛出抑制异常?如果 exec 发送 IOExcption 而我无法捕捉到抛出的原因
  • 不,throws 强制函数的调用者捕获或声明异常。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 2013-08-10
  • 1970-01-01
  • 2012-11-17
  • 2011-02-02
相关资源
最近更新 更多