Try-catch: is this acceptable practice?

前端 未结 8 2131
终归单人心
终归单人心 2020-12-17 17:35

We have received Java code from a software supplier. It contains a lot of try-catch blocks with nothing in the catch part. They\'re all over the pl

8条回答
  •  旧巷少年郎
    2020-12-17 18:13

    Unfortunately you cannot just remove it, because it the try block throws a checked exception then it will have to be declared in the throws clause of the method. The callers of the method will then have to catch it (but not if the callers also have this catch (Exception e) {} abomination).

    As an alternative, consider replacing it with

    try {
        meshContinuum.enable(MeshingModel);
    } catch (Exception e) {
        throw (e instanceof RuntimeException) ? (RuntimeException) e : new RuntimeException(e);
    }
    

    Since RuntimeException (and classes that extend it) are unchecked exceptions they do not need to be declared in the throws clause.

提交回复
热议问题