java public static void main(String[] args)抛出IOException

ogq8wdun  于 5个月前  发布在  Java
关注(0)|答案(4)|浏览(45)

当我们写这个的时候->

void add() throws ArithmeticException

字符串
它表明方法add可能会也可能不会抛出ArithmeticException。所以调用方法必须写try和catch块,来处理这个异常。那么当我们写这个->时,它意味着什么呢?

public static void main(String[] args) throws IOException


即使main方法抛出IOException,也没有调用方法来处理它。那么当我们写main方法抛出异常时,这意味着什么呢?

0tdrvxhp

0tdrvxhp1#

因为IOException是一个checked Exception,main只是一个和其他方法一样的方法,所以如果一个checked Exception在方法中抛出,它必须在方法签名中声明。换句话说,main可能是入口点,但它也可以像任何方法一样被调用,甚至作为入口点,它被JVM中的其他代码调用。

f1tvaqid

f1tvaqid2#

main方法与其他方法没有任何区别。它之所以特殊,是因为它被定义为应用程序的入口点。如果它抛出异常,并且没有处理程序,程序将崩溃并停止运行。然而,有一些情况可以处理main方法。例如:

public class a{
        public static void main(String[] args)throws IOException{
                throw IOException;
        }
}

//some other class:
String[] args = {};
new a().main(args);

字符串

ccrfmcuu

ccrfmcuu3#

public static void main(String[] args)抛出IOException
这意味着main方法没有捕获任何异常,而是通过将IOException抛出到调用main方法的源代码来处理它。
如果你想让它被更高的函数或调用函数处理,你可以抛出Exception
记住,当你抛出Exception的时候,异常不会消失,它仍然需要通过调用函数来处理,否则它会使程序崩溃。
范例:

public void iThrowException() throws Exception{
  throw new Exception("It has to be handled!");
}

字符串
每当你想调用这个方法时,你应该像这样在try/catch块内调用

public void iWillHandleIt(){
  try{
    iThrowException();
  }catch(Exception e){
    System.err.println("Exception caught: "+e);
  }
}


在你的例子中,如果你从main方法抛出Exception,main()方法的调用者,即JVM需要处理异常。否则它将导致崩溃。
你会得到更好的主意,如果你去扔Read more about Checked and UncheckedExceptions here

zu0ti5jz

zu0ti5jz4#

public static void main(String[] Args) throws IOException
{
......
}

字符串
这指定了方法可能会抛出IOException,并坚持编译器调用此方法的块需要特别注意处理或再次抛出。
抛出IOException:main方法中的逻辑执行一些与I/O相关的任务,并且为了确保程序不会由于一些与I/O相关的问题而崩溃,这是一种故障安全。2或者,将负责的代码 Package 在一个try- catch结构中也可以工作。

相关问题