Guava Preconditions RuntimeExceptions handling

As I understood, we use Guava Preconditions to fail fast, before changing some objects states (a nice answer here from stackoverflow). And this is good. However it throws Runtime exceptions and this is not the favorite exceptions for the user of an application (500 errors and so on ...). So I need you to give me some help in design.

I have an interface that declares many methods. Each method has arguments which must be controlled (ex: not null). So in the implementation class I use instructions like the following :

Preconditions.checkNotNull(fooObj);

However the program calling this API might crash due to a runtime exception, that is in this case NullPointerException.

So how do you handle these unchecked exceptions?

Thank you.

-------- EDIT The app layers :

  • Data Access Layer

  • API declaring the methods that exchange DTO

  • Process implementing the API and checking arguments using Guava

  • Webservice depending on the process layer


  • A failure of a precondition means that your program has a bug. Users should not encounter these unless they've found a bug in your program.

    Your program should in general show some kind of error message to users in case of an error, but more to the point, you should get informed so you can fix the bug in the first place.


    You handle them by designing your program to ensure they never happen. These precondition methods are intended to detect bugs and help find exactly where the root cause is, not to verify user input.

    If you are defining only the API, not the programs that call it, then you "handle" it by telling people in your documentation that the arguments in question must not be null, and leave the problem of satisfying that requirement to them.

    If you are writing a calling program as well, first try to make sure the exception just never happens. You can also put the call in a try/catch block to catch the NullPointerException , but the purpose of the catch block should be to give you better notification of the bug (eg record a log message or trigger an alert) and the triggering circumstances, and possibly to shut down more gracefully or give a more user friendly error message. Attempting to recover from the failure should be done with great care or not at all - if this kind of failure happens then something has gone wrong that you did not foresee, and the proper way to recover may not be predictable.

    链接地址: http://www.djcxy.com/p/76238.html

    上一篇: 何时抛出IllegalStateException与IllegalArgumentException?

    下一篇: Guava Preconditions RuntimeExceptions处理