java捕获异常

java捕获异常,java,Java,我在上面包含代码的方法中得到编译错误,是否有任何方法在else块中抛出InputMismatchException?声明它所在的方法以抛出异常 try{ method(); } catch (InputMismatchException ime){ //do what you want } 因为OutputStream.close()抛出IOException您也需要抛出它: try { if (x.length == Styles.size()) {

我在上面包含代码的方法中得到编译错误,是否有任何方法在else块中抛出InputMismatchException?

声明它所在的方法以抛出异常

try{
  method();
} catch (InputMismatchException ime){
   //do what you want
 }
因为
OutputStream.close()
抛出
IOException
您也需要抛出它:

    try {
        if (x.length == Styles.size()) {

        }
        else{
             throws InputMismatchException ;
        }
    } finally {
        OutputFileScanner.close();
    }

声明它所在的方法以引发异常

try{
  method();
} catch (InputMismatchException ime){
   //do what you want
 }
因为
OutputStream.close()
抛出
IOException
您也需要抛出它:

    try {
        if (x.length == Styles.size()) {

        }
        else{
             throws InputMismatchException ;
        }
    } finally {
        OutputFileScanner.close();
    }

当您抛出异常时,就没有必要尝试最终捕获它。在捕获异常时,try catch finally是必需的。请尝试以下操作--


当您抛出异常时,就没有必要尝试最终捕获它。在捕获异常时,try catch finally是必需的。请尝试以下操作--

“throws”声明不在方法体中。如果只想抛出异常,请按如下方式声明它:

if (x.length == Styles.size()) {

    }
    else{
         throw new InputMismatchException() ;
    }
这里不需要使用try语句。调用方法()时,将使用以下命令:

    public void method() throws InputMismatchException{

    if(...) {...
     OutputFileScanner.close();
   }
    else{
      OutputFileScanner.close();
     throw new InputMismatchException("Uh oh");
      }
    }
希望有帮助

方法体中没有“throws”声明。如果只想抛出异常,请按如下方式声明它:

if (x.length == Styles.size()) {

    }
    else{
         throw new InputMismatchException() ;
    }
这里不需要使用try语句。调用方法()时,将使用以下命令:

    public void method() throws InputMismatchException{

    if(...) {...
     OutputFileScanner.close();
   }
    else{
      OutputFileScanner.close();
     throw new InputMismatchException("Uh oh");
      }
    }

希望有帮助

您想创建一个异常实例,然后抛出它<代码>抛出用作方法声明的一部分,而不是实际抛出异常

try{
  method();
} catch (InputMismatchException ime){
   //do what you want
 }

您想创建一个异常实例,然后抛出它<代码>抛出用作方法声明的一部分,而不是实际抛出异常

try{
  method();
} catch (InputMismatchException ime){
   //do what you want
 }

您需要使用
new
关键字:

    if (x.length == Styles.size()) {

    }
    else{
         throw new InputMismatchException();
    }

您需要使用
new
关键字:

    if (x.length == Styles.size()) {

    }
    else{
         throw new InputMismatchException();
    }

它可能只是抱怨您没有声明您的函数可能抛出InputMismatchException。尝试在函数定义的末尾添加“throws-inputmashtachexception”。这可能只是抱怨您没有声明您的函数可以抛出inputmashtachexception。尝试将“throws-inputmaschException”添加到函数定义的末尾。他需要关闭扫描仪以防止资源泄漏,因此建议他不需要这是完全错误的。我是在评论异常处理的w.r.t。显然,他需要释放资源。谢谢。他需要关闭扫描仪以防止资源泄漏,所以建议他不需要这是完全错误的。我是在评论异常处理的w.r.t。显然,他需要释放资源。谢谢。所有这些“声明
抛出
”的答案和一切,嘘,我想我必须回答这个问题
InputMismatchException
甚至不是选中的异常,它是
RuntimeException
的子类+1是的,保留了
运行时异常
位,因为OP可能根本没有声明它(或者至少不应该声明)。所有这些“declare
抛出
”回答了所有问题,sheesh,我想我必须回答这个问题
InputMismatchException
甚至不是选中的异常,它是
RuntimeException
的子类+1是的,保留了
RuntimeException
位,因为OP可能没有声明它(或者至少不应该声明)。