首页 > 解决方案 > 我如何处理以下代码示例中的异常。?

问题描述

下面是可能返回 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;
    }**

标签: javaexception

解决方案


根据彼得·杜尼霍的评论......

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


推荐阅读