我经常使用异常来进行流程控制,但我有一种奇怪的感觉,我做错了什么。编写如下所示的代码是一个好习惯吗?
public static void main(String[] args)
{
try
{
methodA();
}
catch (Exception ex)
{
handleException(ex);
}
}
public static methodA()
{
methodB();
}
public static methodB()
{
if(someConditionIsNotMet)
{
throw new RuntimeException("Some Condition Is Not Met");
}
}
最佳答案
I use exceptions to flow control a lot
抛出特定的功能异常来指示工作流程中的功能问题本身并不坏。
这不是唯一的方法,但它是一种有效的方法。
另一种方法依赖于返回 boolean
的方法并测试返回的值。
就我个人而言,我不使用这种方式,因为我发现它相当冗长,容易出错(我们不要忘记测试返回的 boolean 值)并且表达能力较差(它只有两个值:true
和false
)比异常(它可能有所需的数量)。
假设方法 B 必须检查某些内容,如果检查失败,则应停止处理并向客户端通知该问题,为此目的使用异常是完全有效的。
现在,将异常设置为特定异常比 Exception
更有意义。
否则客户端如何解释异常含义?
该异常可能是工作流异常,但也可能是由于其他原因在运行时引发的任何异常,例如 NullPointerException
。
您希望以特定方式处理工作流异常,但不会对其他抛出的异常应用特定处理。
例如,您可以将其写为:
public static methodA()
{
methodB();
}
public static methodB(){
if (!expectedDataFound()){
throw new DataNotFoundException("data xxx was not found");
}
if (!hasRights()){
throw new PermissionException("user xxx has not the rights for yyy");
}
}
那么从客户端来看,你有两种方法。
单独捕获每个异常或以通用方式捕获它们(只有当它们属于同一层次结构时才可能)。
单独捕获每个异常:
public static void main(String[] args)
{
try
{
methodA();
}
catch (DataNotFoundException ex)
{
handleDataNotFoundException(ex);
}
catch (PermissionException ex)
{
handlePermissionException(ex);
}
}
全局捕获异常:
public static void main(String[] args)
{
try
{
methodA();
}
catch (WorkflowException ex)
{
handleWorkflowException(ex);
}
}
关于java - 异常流控,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47711379/