0

I learning exception handling in JAVA, I found that exceptions/errors can also be classified on the basis of who throws or raises it.

  1. Exceptions raised by JVM

  2. Exceptions raised by API developer/programmer

My question is who is responsible for raising AssertionError?

Holger
  • 285,553
  • 42
  • 434
  • 765
  • Welcome to Stack Overflow. Have a look at already existing Q/As on the site. For example [Avoiding != null statements](https://stackoverflow.com/questions/271526/avoiding-null-statements/271874#271874) is about using ``AssertionError`` – from which I think you can answer your question yourself. – Ivo Mori May 27 '20 at 04:36
  • Note that your question may also be better suited for the [Software Engineering](https://softwareengineering.stackexchange.com) stack exchange. There you'll find for example [When to use assertions and when to use exceptions?](https://softwareengineering.stackexchange.com/questions/15515/when-to-use-assertions-and-when-to-use-exceptions). Plenty of information out there, ___just search for it___ – otherwise make it clear why already existing Q/As don't answer your question – and be sure to ask a very specific (not yet asked) question. – Ivo Mori May 27 '20 at 04:38
  • Have a look at [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask). – Ivo Mori May 27 '20 at 04:39
  • In the end it’s the programmer. She often does that indirectly through something like `assert s.length() == expectedLengh;`, which only throws if assertions are enabled. She may also do it directly: `throw new AssertionError("This can’t happen");`. – Ole V.V. May 27 '20 at 05:18

1 Answers1

3

The responsibility lies at the programmer regardless of whether they use, e.g.

throw new AssertionError("unreachable code");

or

assert condition;

Note that the assert statement is so called “syntactic sugar”.

When you write

class ClassWithAssert {
    public ClassWithAssert() {
        assert toString() != null;
    }
}

It gets compiled to the equivalent of

class ClassWithAssert {
    static final boolean $assertionsDisabled
        = !ClassWithAssert.class.desiredAssertionStatus();
    public ClassWithAssert() {
        if(!$assertionsDisabled && toString() == null)
            throw new AssertionError();
    }
}

So the implicit throwing is not different to the explicit one, technically.

Holger
  • 285,553
  • 42
  • 434
  • 765