IllegalArgumentException + 继续避免破坏程序?

时间:2021-07-24 18:00:55

标签: java break illegalargumentexception continue

我想问一下是否有可能阻止 IllegalArgumentException 中断程序运行。如果我这样做:

throw new 
IllegalArgumentException("Value not 
allowed!");
continue;

这会阻止IAE在触发异常后破坏程序吗?如果没有,有什么方法可以将其作为错误消息抛出给用户,然后让他们继续运行程序而无需重新运行?

2 个答案:

答案 0 :(得分:5)

  1. 如果要处理异常(即阻止程序终止),必须使用 try/catch 块。

  2. 每当抛出异常时,控制立即退出。您的“继续”语句执行。

  3. 当您“捕获”异常时,您可以重新抛出它。您可能会在代码中的某个更高级别有另一个 try/catch 块。

  4. 您的最佳策略是“防御性编码”并首先尝试防止 IllegalArgumentException 发生。

  5. 最后,您永远不想丢失信息。

    /*
     * Poor: 
     * *WHAT* value???  Where did this occur?  Why?
     * You've just lost all this information, "Value not allowed" is uselessly vague...
     */
    throw new IllegalArgumentException("Value not allowed!");
    

答案 1 :(得分:1)

要么使用 try..catch 结构来“拦截”异常,要么首先不抛出异常。

相关问题