Will an assertion error be caught by in a catch block for java exception?

You have almost answered your own question. Your catch block will not catch the AssertionError that the Assert throws if it fails, because it is an Error (or, more specifically, it extends java.lang.Error). See the docs for more information on this. Your catch block only catches Throwable objects that extend java.lang.Exception

If you really want to catch it – you need to use

catch (AssertionError e) {
...

However, as others have mentioned, this is a very unusual way to use assertions – they should usually pass and if they fail it is very unusual for you to want to carry on the program execution. That’s why the failure throws an Error rather than an Exception. You can read more about (not) catching Error in this question.

If you just want a test the variable value, it is preferred to use if ( variableName == "1")

NB if you are testing unit-test helper code, like a matcher, it might make sense to catch the AssertionError.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)