尝试/捕获内部或外部功能 [英] Try/Catch inside or outside functions

查看:73
本文介绍了尝试/捕获内部或外部功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于使用 try / catch 的最佳实践,我有一个非常基本的问题。
我有一个简单的函数(DAO)

I have a very basic question about best practice of using try/catch. I have a simple function (DAO) like this

public void addVehicle(Vehicle vehicle) {

    em.getTransaction().begin();
    em.persist(vehicle);
    em.getTransaction().commit();
}

并在Web服务中使用DAO功能:

and using DAO function inside web service:

@WebMethod(operationName = "addVehicle")
public void addVehicle(Vehicle vehicle) {

    try {
        vehicleDAO.addVehicle(vehicle);
        System.out.print("Vehicle added");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

使用 try更好 / catch 在DAO函数中是这样的:

OR is better using try/catch inside DAO function like this:

public void addVehicle(Vehicle vehicle) {

    try {
        em.getTransaction().begin();
        em.persist(vehicle);
        em.getTransaction().commit();
    } catch (Exception e) {
        e.printStackTrace();
    }
}


推荐答案

有这不是完美的规则。

There is no perfect rule for that.

如果在需要的情况下尽早捕获异常,但要尽可能晚地捕获异常,通常代码会更清晰,更简单。
您应该考虑当 Exception 发生时,谁必须采取行动,这决定了您是否抓住它在方法(addVehicle)中,或者如果您抛出,则调用方必须 catch 来实现。

Often code is clearer and less complex if exceptions are catched as early as needed, but as late as possible.
You should think who has to take an action when that Exception happens, this decides if you catch it inside the method (addVehicle) or if you throw it such that the caller has to catch it.

例如:

 public void addVehicle(Vehicle vehicle) throws SQLException{
        em.getTransaction().begin();
        em.persist(vehicle);
        em.getTransaction().commit();
 }

在此示例中,呼叫者必须接听。

此外,仅在少数情况下,您应该捕获 Exception RunTimeException ,更好的
捕获该特定的异常,例如 IOException 而不是 Exception

In this example the caller has to catch.
Further only in few situations you should catch Exception or RunTimeException, better catch that specific Exception, like IOException instead of Exception.

某处您的代码将需要一个最后一道防线,在这种情况下, catch(异常例外)才有意义。这是处理不应该发生的错误所必需的。

Somewhere in your code you will need a "last line of defense" where it make sense to catch (Exception ex). This is needed to handle errors that should not happen.

这篇关于尝试/捕获内部或外部功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆