Best practices for catching Throwable in Java

后端 未结 4 1491
孤城傲影
孤城傲影 2021-02-05 17:41

Sometimes, you just have to catch Throwable, e.g. when writing a dispatcher queue that dispatches generic items and needs to recover from any errors (said dispatcher logs all ca

4条回答
  •  清酒与你
    2021-02-05 17:45

    Probably the most important one is, never swallow a checked exception. By this I mean don't do this:

    try {
      ...
    } catch (IOException e) {
    }
    

    unless that's what you intend. Sometimes people swallow checked exceptions because they don't know what to do with them or don't want to (or can't) pollute their interface with "throws Exception" clauses.

    If you don't know what to do with it, do this:

    try {
      ...
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
    

    The other one that springs to mind is to make sure you deal with exceptions. Reading a file should look something like this:

    FileInputStream in = null;
    try {
      in = new FileInputStream(new File("..."));;
      // do stuff
    } catch (IOException e) {
      // deal with it appropriately
    } finally {
      if (in != null) try { in.close(); } catch (IOException e) { /* swallow this one */ }
    }
    

提交回复
热议问题