Over a million developers have joined DZone.

Using Java Assertions? Use an Assertion-failed Breakpoint!

· Java Zone

What every Java engineer should know about microservices: Reactive Microservices Architecture.  Brought to you in partnership with Lightbend.

I'm a big fan of assertions. I use them very often in my code as safeguards. I was very pleased when true, native assertions were introduced to Java: they allow adding more tests while keeping the code running faster when disabled. 

If you like assertions, you will appreciate the following tip. A failed assertion will throw a java.lang.AssertionError runtime exception. Logging the assertion failures is up to the application code. If your code does not report this error properly, you may completely miss the assertion failures. 

Eclipse has a very useful mechanism for breaking on Exceptions. It's a different kind of breakpoint, which is triggered when the exception is thrown, regardless of how (and if) it is caught. If you are using assertions, I highly recommend setting a breakpoint on assertion failures when debugging your code. Here's how:

 

  1. From the Run menu, select Add Java Exception Breakpoint...
  2. Type java.lang.AssertionError in the dialog box, select the exception and click OK.

That's it, you are done. From now on, the debugger will stop whenever an exception is throw. The breakpoint will appear in the breakpoints view. You can right click it and select Breakpoint Properties... to see all the settings you can control.

Eclipse-exception-breakpoint The most useful feature would be to break on uncaught exceptions only, although, in case of assertions, I would break in any case.

Needless to say, the exception breakpoints can be used for any kind of exception. Truly a hidden treasure worth adding to your toolbox.
 

Microservices for Java, explained. Revitalize your legacy systems (and your career) with Reactive Microservices Architecture, a free O'Reilly book. Brought to you in partnership with Lightbend.

Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}