3

How can I replace assertions with ifs? Example:

public Wezel<Wartosc,Indeks> getWujek() { assert rodzic != null; // Root node has no uncle assert rodzic.rodzic != null; // Children of root has no uncle return rodzic.getBrat(); } 
2
  • Out of curiosity, why do you want to do this? Commented Dec 11, 2011 at 17:41
  • I'm not quite sure about it's semantic correctness, and i want to make it better. Commented Dec 11, 2011 at 18:14

3 Answers 3

6

An assertion is roughly equivalent to:

if (!condition) { throw new AssertionError(); } 
Sign up to request clarification or add additional context in comments.

2 Comments

besides that assertions only work when the -ea switch is passed to the JVM
I suppose this answer is the best one, because i don't have to catch AssertionError().
2
public Wezel<Wartosc,Indeks> getWujek() { if(rodzic == null) { // Root node has no uncle throw new Exception("Root node has no uncle"); } if(rodzic.rodzic == null) { throw new Exception("Children of root have no uncle"); } return rodzic.getBrat(); } 

Comments

2

Replacing these assertions would take the form of the following validation:

if (rodzic == null) throw new MyValidationException("rodzic cannot be null"); if (rodzic.rodzic == null) throw new MyValidationException("rodzic.rodzic cannot be null"); return rodzic.getBrat(); 

Note that there's a distinction between throwing an Exception and an Error - Exceptions are meant to be caught and handled farther up, while Errors indicate a situation that you can't recover from. For example, you might consider a defining and using a MyValidationError if the failed check is irrecoverable.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.