java.lang.Exception vs. rolling your own exception

后端 未结 10 1206
无人及你
无人及你 2020-12-13 14:30

At what point would you create your own exception class vs. using java.lang.Exception? (All the time? Only if it will be used outside the package? Only if it must contain ad

10条回答
  •  醉话见心
    2020-12-13 15:11

    Reason one:

    Need to catch specific stuff. If calling code needs to deal with a specific exceptional condition, you need to differentiate your Exception, and Java differentiates exceptions with different types, so you need to write your own.

    Basically, if someone has to write:

    catch(ExistingException e) {
      if({condition}) {
        { some stuff here}
      }
      else {
        { different stuff here}
      }
    }
    

    You probably want to write a specific extension; catch Exception matching is clearer than conditionals, IMHO.

    Remember: your new Exception can be a subclass of RuntimeException

    Reason two:

    API consolidation. If you write an interface and you have several implementations, it's possible that they will call different APIs with a whole bunch of different non-RuntimeExceptions thrown:

    interface MyInterface {
      void methodA();
    }
    
    class MyImplA {
      void methodA() throws SQLException { ... }
    }
    
    class MyImplB {
      void methodA() throws IOException { ... }
    }
    

    Do you really want MyInterface.methodA to throw SQLException and IOException? Maybe then it makes sense to wrap the possible exceptions in a custom Exception. Which again can be a RuntimeException. Or even RuntimeException itself...

提交回复
热议问题