How to catch an assertion error in Java


In order to catch the assertion error, we need to declare the assertion statement in the try block with the second expression being the message to be displayed and catch the assertion error in the catch block.

Let us see a program on how to handle Assertion Error in Java −

Example

public class Example {
   public static void main(String[] args) throws Exception {
      try {
         assert args.length > 0 : "Assertion error caught!!!!";
      }
      catch (AssertionError e) {
         System.out.println(e.getMessage());
      }
   }
}

Output

Updated on: 25-Jun-2020

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements