java - 我如何处理以下代码示例中的异常。?
问题描述
下面是可能返回 IndexOutofBounds 异常的方法。我想使用 try 和 catch 而不是 throws 来处理异常。请帮我。
我试过try and catch,但是我应该在哪里使用return语句,是在try还是catch之后。
**@RequestMapping(value = "/hospitals/{id}", method = RequestMethod.GET)
public @ResponseBody Hospital getHospital(@PathVariable("id") int id){
Hospital hospital = this.hospitalService.getHospital(id);
return hospital;
}**
解决方案
根据彼得·杜尼霍的评论......
public Hospital getHospital(int id) {
Hospital hospital = null;
try {
hospital = hospitalService.getHospital(id);
}
catch (Exception x) {
x.printStackTrace();
}
return hospital;
}
如果里面的行try
抛出异常,那么堆栈跟踪将被写入控制台,并且该方法将返回 null。
如果 中的行try
没有抛出异常,则该方法将返回Hospital
具有给定 的对象id
。
推荐阅读
- c# - 如何将设备管理器设备属性获取到文本框?
- javascript - CSS如何强制一个新的div低于前一个,因为宽度不适合
- angular - 在带有角度的离子打字稿中获取警报控制器中的输入值
- r - 用另一个向量中的一个替换每个值 - dplyr
- android - 在 Android WebView 中使用 OAuth 进行社交登录
- android - Firebase 云消息传递通知 remoteMessage.data 为空
- ios - 如何为 UIView 关键帧动画设置动画曲线(`func UIView.animateKeyframes()`)
- php - Laravel 注册密码验证
- flutter - 主题 TextField 工具栏选项
- java - Config.getString() 和 configurationService.getConfiguration().getString() 有什么区别