Exception Vs Assertion
Use assertions for internal logic checks within your code, and normal exceptions for error conditions outside your immediate code's control.
Don't forget that assertions can be turned on and off - if you care about things like argument validation, that should be explicit using exceptions. (You could, however, choose to perform argument validation on private methods using assertions, on the grounds that a violation at that point is due to an internal bug rather than an external error.)
Alternatively it's entire reasonable (IMO) to use exceptions for everything. I personally don't use assertions much at all, but it's a matter of personal preference to some extent. (There can certainly be objective arguments for and against assertions, but it's not sufficiently clear cut to remove preference altogether.)
Java assertions are built on top of Java exceptions and exception handling. Indeed, when a Java assertion fails, the result is an AssertionError exception that can be caught like any other Java exception. The key differences between exceptions and assertions are:
- 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.
The Java language provides syntactic support for assertions, in the form of the
assert
statement. Compare the following:if (x != y) { throw new SomeException("x != y"); } assert x != y;
Most importantly, Java allows you to enable or disable assertion checking globally or on individual classes when you start the JVM.
Note: some people say that you should always run production code with assertion checking turned off. I tend to disagree with this as a blanket statement. If your production code is known to be stable AND you need to squeeze that last bit of performance out of it, then turning off assertions is good. But, if a (say) 10% performance hit is not a real problem, I'd prefer to have an application die with an assertion error if the alternative is continue and corrupt my database.
@Mario Ortegón commented thus:
The "turning off" is because assertions can be used to verify the result of an optimized algorithm by comparing its implementation against a well-known, but slow, algorithm. So, in development it is OK to invoke that
O(N^3)
method to assert that theO(log N)
algorithm works as intended. But this is something that you do not want in production.
Whether or not you think it is good practice to turn off assertions in production, it is definitely bad practice to write assertions that have a significant impact on performance when enabled. Why? Because it means that you no longer have the option of enabling assertions in production (to trace a problem) or in your stress / capacity testing. In my opinion, if you need to do O(N^3)
pre/post-condition testing, you should do it in your unit tests.
Exception is a mechanism of checking if the implementation is executing without any expected or unexpected errors or not. So, we see that exceptions are basically used for handling even the unforseen conditions during the execution of an application in a better way and hence using exceptions effectively results into a robust application.
Assertions should never be a part of the implementation of some functionality of the application. They should only be used to verify the assumptions - just to be sure that whatever we assumed while desinging the solution is actually valid in practical as well.
reference: http://geekexplains.blogspot.com/2008/06/asserions-in-java-assertions-vs.html
Assertions are very similar to exceptions, in fact just like exceptions they will flag a problem, but unlike exceptions - they won’t suggest any alternative execution path, but will simply fail. Why use assertions, if you can do the same thing, plus more with exceptions ?
Use them when the problems should not be fixed, and actually SHOULD NEVER HAPPEN IN THE FIRST PLACE. This sounds weird at first: don’t we want to safeguard our code from ALL potential problems ? Usually yes. But there is a case where we don’t. This case is called: “Design by contract”.
Let say you are writing an application for a bank. As a developer you can not possibly support all possible financial conditions. So before starting to code, you get a spec from the bank which gives you the valid ranges that this application should support. So your application is designed by a contract (by the spec from the bank). This contract will define the fundamental principles that should always be true in order for your application to work. These fundamental principles are called “invariants” (because they can’t change). Design by contract simplifies your life as a developer - you are only responsible to support the scope of work defined in the contract.
Its important to check the values of these invariants in your code, but you shouldn’t check them as if they are exceptions and try to work around them. If they are wrong - you must fail because the inputs have not fulfilled their contractual obligations.
The interesting thing is: if you don’t put an assertion into the critical place and invariants become invalid - your code will fail anyway. You just won’t know why. So to summarize - assertions are used for verifying the invariants. They go hand-in-hand with the “design by contract” principle. Use them to debug a problem, thats why they are turned off in production.
Another use case: if you are relying on an external library that you don’t completely trust - you may want to use assert statements when calling it.
Some also use assertions as a quick and dirty substitute for an exception (since its so easy to do), but conceptually that is not the proper thing to do.