Contents
Why are exceptions better than assert statements?
Java assertions are built on top of Java exceptions and exception handling. Assertions are intended to be used solely as a means of detecting programming errors, aka bugs. By contrast, an exception can indicate other kinds of error or “exceptional” condition; e.g. invalid user input, missing files, heap full and so on.
Should I use assert in production code?
When to Assert Incorrect assumptions about how a function will be used are a common cause of subtle bugs . My general rule is: If there is no else statement, there should be an assertion. This is easy to add and also helps document assumptions in the code.
When to throw illegalargumentexception over assertions?
I always prefer to throw IllegalArgumentException over assertions. Assertions are used mostly in JUnit or other testing tools, to check/assert test results. So it might give false impression to other developers that your method is a test method.
When to throw illegalargumentexception In JUnit test?
Assertions are used mostly in JUnit or other testing tools, to check/assert test results. So it might give false impression to other developers that your method is a test method. Also it makes sense to throw IllegalArgumentException when a method has been passed an illegal or inappropriate argument.
Can a Java assertion be used in production?
Java Assertions are not to be used on production code and should be restricted to private methods (see Exception vs Assertion), since private methods are expected to be known and used only by the developers.
When is an argumentexception thrown in a program?
ArgumentException is thrown when a method is invoked and at least one of the passed arguments does not meet the parameter specification of the called method. All instances of ArgumentException should carry a meaningful error message describing the invalid argument, as well as the expected range of values for the argument.