Java - 如何在异常时保持 运行

Java - How to keep running on exception

这个问题看起来很简单。如何使我的应用程序保持 运行 异常状态。

例如,我将如何去做。

服务器应用程序尝试 运行 端口 1234,但它不可用。通常它只会崩溃。但是我怎样才能让它保持 运行ning 并说;您想尝试另一个端口吗?

或者如果我们试图加载一个不存在的文件。如何避免程序崩溃,但只显示一条小消息说它无法加载文件。

这是怎么做到的?

使用 try catch block.

try{
 //Where exception may happen
}catch(Exception e){//Exception type. Exception covers it all.
 //Print error if you would like or do something else
}finally{//Finally is optional, as the code in here will run regardless of an exception.
}
//program continues

大多数 try-catch 块的末尾都没有 finally。如果您需要代码为 运行(无论是否有异常),您将使用 finallyMore information about the finally block

这是一个 catch 会失败但 finally 执行的示例:

int number = 0;

try {
    number = 1 / 0;
} catch (IndexOutOfBoundsException e) {
    System.out.println("Nooooo!");
} finally {
    System.out.println("What just happened?");
}

System.out.println(number);

这输出:

What just happened?
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ...

catch 未能执行,因为它仅捕获 IndexOutOfBoundsExceptions 而不是 ArithmeticExceptions,这是您尝试除以零时得到的结果。

我遇到了同样的问题,但我的情况是二叉树 class 抛出的异常终止了程序,我希望它继续 execution.So,你的问题可以通过下面的写法解决代码。

do{
try{
    //get the value for port 
    //it may throw exception

  }
 catch(Exception e){
   // handle exception
  }
 //ask for yes or no to continue
}while(choice);    

好吧,只要您 want.Use 循环连续询问端口值,它就会一直询问端口值。

记住:您可以在 catch 块之后添加代码,但不能在 try 和 catch 块之间添加代码。