Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception Vs Assertion

Tags:

java

assert

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?

like image 847
JavaResp Avatar asked Aug 14 '09 06:08

JavaResp


People also ask

Why are exceptions better than assertions?

Exceptions versus assertions Use assert statements to test for conditions during development that should never be true if all your code is correct. There's no point in handling such an error by using an exception, because the error indicates that something in the code has to be fixed.

Is assertion error an exception?

Errors are not Exceptions. Specifically, AssertionError is not a subclass of RuntimeException, so it is not an unchecked exception.

What are the 3 types of exceptions?

There are three types of exception—the checked exception, the error and the runtime exception.

What is difference between exception & error?

The error indicates trouble that primarily occurs due to the scarcity of system resources. The exceptions are the issues that can appear at runtime and compile time. 2. It is not possible to recover from an error.


1 Answers

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.)

like image 176
Jon Skeet Avatar answered Sep 17 '22 11:09

Jon Skeet