java - 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);}
?
解决方案
更喜欢在 try/catch 子句中“包装”switch 语句。
主要思想是
- 通过 switch 子句以直接的方式表达逻辑
- 如果您打算处理异常,请将其包装在 try/catch 块中。
推荐阅读
- reactjs - 如何在 MSAL 反应路由器中保存登录状态?
- mysql - NodeJs docker 容器无法连接 MySQL 服务器
- kotlin - 如何从“日期”格式的 DateTime Picker 获取日期和时间(不是当前的)?
- react-native - 在 React Native 表中显示 json 数据
- ios - 如何在 Swift 中使用 beginBackgroundTask 和 endBackgroundTask
- java - 如何使用 BufferedReader 类从用户那里获取字符和字符串输入?
- java - BLE,如何停止扫描
- c++ - Arduino Nano 33 IoT & NEO 6M GPS 模块
- three.js - 从 Blender 到三个 js 的 3d 模型遇到问题
- statistics - 我们如何对连续 X 和 Y 变量进行假设检验