java – Exception Vs Assertion-ThrowExceptions

Exception or error:

What is the difference between Java exception handling and using assert conditions?

It’s known that Assert is of two types. But when should we use assert keyword?

How to solve:

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 the O(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.



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.


Example of a good use of Assert:

assert flibbles.count() < 1000000; // too many flibbles indicate something is awry
log.warning("flibble count reached " + flibbles.count()); // log in production as early warning

I personally think that Assert should only be used when you know something is outside desirable limits, but you can be sure it’s reasonably safe to continue. In all other circumstances (feel free point out circumstances I haven’t thought of) use exceptions to fail hard and fast.

The key tradeoff for me is whether you want to bring down a live/production system with an Exception to avoid corruption and make troubleshooting easier, or whether you have encountered a situation that should never be allowed to continue unnoticed in test/debug versions but could be allowed to continue in production (logging a warning of course).

cf. see also my c# copy of this answer: Debug.Assert vs. Specific Thrown Exceptions


Assert is for debugging purpose only and its trigger condition should not happen (null pointer when there shouldn’t be, etc.)

Exception is for special system events that may always happen : FileNotFound, ConnectionToServerLost, etc.


Assertion and Exception Handling both can assure programme correctness and avoid logic error,

but assertion can enable and disable as programmer wish,

in compiler if you use “java -ea JavaFileName” or “java -enableasserations JavaFileName”
you can compile with assertion

if programmers don’t need it ,”java -da JavaFileName ” or “java -disableasserations JavaFileName ” they can disable assertion.

this facility not in Exception handling


Assertion is used for debugging of the required assumptions to be checked at runtime only by enabling the assert feature while exception is to check the specific conditions to be checked during execution of the program to prevent the program from terminating.


Although, I have posted the answer in se.stackexchange site, that might be still helpful to post here.

Assertions are used,

  1. When you want to stop the program immediately rather to proceed with an unwanted state. This is often related to the philosophy of the Fail-fast [ 1 ] system design.

  2. When there are certain possibilities of cascading failures (i.e. in microservices) for the first unexpected condition that might lead the application into severe inconsistent or unrecoverable states.

  3. When you want to detect bugs in your system exclusively in the debugging period. You might want to disable them in production if language supports.

  4. When you already know that the unexpected conditions arose due to your internal miss-implementation and external system (i.e the callers) has no control over the unwanted state.

Exceptions are used,

  1. When you know that the unexpected conditions arose due to external systems fault (i.e. wrong parameters, lack of resources etc).

  2. When you know that the conditions can be backed up with alternative paths keeping the application functional qualities still intact (i.e. might work well for another call with proper parameters from the caller or external system).

  3. When you want to log and let the developers know about some unwanted state but not a big deal.

Note: “The more you use assertions, the more robust system you get”. In contrast “The more you use exceptions and handle them, the more resilient system you get“.

[ 1 ] Fail fast – In systems design, a fail-fast system is one which immediately reports at its interface any condition that is likely to indicate a failure. Fail-fast systems are usually designed to stop normal operation rather than attempt to continue a possibly flawed process. Such designs often check the system’s state at several points in an operation, so any failures can be detected early. The responsibility of a fail-fast module is detecting errors, then letting the next-highest level of the system handle them.

Leave a Reply

Your email address will not be published. Required fields are marked *