问题描述
我想问一下是否有可能阻止 IllegalArgumentException 中断程序运行。如果我这样做:
throw new
IllegalArgumentException("Value not
allowed!");
continue;
这会阻止IAE在触发异常后破坏程序吗?如果没有,有什么方法可以将其作为错误消息抛出给用户,然后让他们继续运行程序而无需重新运行?
解决方法
-
如果要处理异常(即阻止程序终止),必须使用 try/catch 块。
-
每当抛出异常时,控制立即退出。您的“继续”语句未执行。
-
当您“捕获”异常时,您可以重新抛出它。您可能会在代码中的某个更高级别有另一个 try/catch 块。
-
您的最佳策略是“防御性编码”并首先尝试防止 IllegalArgumentException 发生。
-
最后,您永远不想丢失信息。
/* * 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!");
要么使用 try..catch
结构来“拦截”异常,要么首先不抛出异常。