Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use assert in android?

I want to use assert obj != null : "object cannot be null" on Android device. The assert doesn't seem to work, so I searched online and I found this local solution:

adb shell setprop debug.assert 1

it does work on my local machine.

I want to run this command using my Eclipse project(so it would be in the source control). How can I do it?

like image 689
Adibe7 Avatar asked May 30 '11 12:05

Adibe7


People also ask

What is assert in Java Android?

assert is a Java keyword used to define an assert statement. An assert statement is used to declare an expected boolean condition in a program. If the program is running with assertions enabled, then the condition is checked at runtime. If the condition is false, the Java runtime system throws an AssertionError .

What does assert () do in Java?

An assertion is a statement in Java which ensures the correctness of any assumptions which have been done in the program. When an assertion is executed, it is assumed to be true. If the assertion is false, the JVM will throw an Assertion error. It finds it application primarily in the testing purposes.

What is assert use for?

The assert keyword is used when debugging code. The assert keyword lets you test if a condition in your code returns True, if not, the program will raise an AssertionError. You can write a message to be written if the code returns False, check the example below.

Is it good practice to use assert?

Yes it is a very good practice to assert your assumptions. Read Design By Contract. assert can be used to verify pre conditions, invariants and post conditions during integration and testing phases. This helps to catch the errors while in development and testing phases.


1 Answers

Assert won't work in Android because most of the time a person isn't running in debug mode, but rather some optimized code. Thus, the proper solution is to manually throw an exception, with code like this:

if (obj==null) throw new AssertionError("Object cannot be null"); 

It should be noted that by design, Asserts are intended for debug code, and not for release time code. So this might not be the best use of throwing an Assert. But this is how you can do it still, so...

like image 147
PearsonArtPhoto Avatar answered Sep 22 '22 14:09

PearsonArtPhoto