If catching null pointer exception is not a good practice, is catching exception a good one?

后端 未结 6 1704
故里飘歌
故里飘歌 2020-12-03 01:56

I have heard that catching NullPointerException is a bad practice, and i think it is sensibly so. Letting the NullPointerException to propagate to

6条回答
  •  春和景丽
    2020-12-03 02:19

    In general, the only times you should catch an exception is if you can handle it in some meaningful way. If you can't you should simply let it bubble to the top and terminate the process. For instance, could you recover in some meaningful way from a NullPointerException or I/O error? I think not.

    My rules for exception handling:

    • In general, don't catch exceptions, unless you can handle them in some meaningful way.
    • Catch exceptions at process/machine boundaries, log the caught exception along with any context available to you and re-throw it. If the exception is a custom exception, you may wrap it in an exception of a type known/useful to the invoking process and throw that.
    • You may also catch exceptions at a low level, where you have the most runtime context available, log the exception and associated context, then rethrow the exception.
    • When rethrowing, use throw ; rather than throw caughtException ;. Use of the former syntax preserves the original stack trace; use of the latter syntax creates a new stack trace, beginning with throw caughtException ; -- you lose all the context and call stack up to the point at which the exception was caught.
    • You may, if you so choose, catch exceptions at a high level and gracefully terminate the process, logging the exception information so as to help debug and correct the underlying problem.

    Do not use exceptions as a flow control mechanism (if possible). Exceptions are supposed to be, well, exceptional in nature. Rather, premptively, enforce the caller's end of the contract (preconditions) for any methods you are invoking.

    See Bertrand Meyers' book , Object Oriented Software Construction, 2nd ed. for more information.

提交回复
热议问题