首页 > 解决方案 > switch 语句中的 try/catch 子句

问题描述

使用 switch 语句时,我是否应该在该案例中捕获与案例相关的异常?或捕获 switch 语句之外的所有相关异常?前任。

 try{
 switch(){
                   case 1:
                   case 2:
                   case 3:
         }
 catch(WrongDataException ex{sysout(ex);}

要不然:

switch{ 
case 1: 
try{
}catch(WrongDataException ex{sysout(ex);}
break;
case 2:
try{
}catch(YouNeedToPayAttentionException ex){sysout(ex);}

?

标签: javaexceptionexception-handlingswitch-statement

解决方案


更喜欢在 try/catch 子句中“包装”switch 语句。

主要思想是

  1. 通过 switch 子句以直接的方式表达逻辑
  2. 如果您打算处理异常,请将其包装在 try/catch 块中。

推荐阅读