Assertions: Difference between revisions

From Rosetta Code
Content added Content deleted
(Created task with Java, maybe C and C++ later if no one else gets to it)
 
(added python)
Line 7: Line 7:
int a;
int a;
//...input or change a here
//...input or change a here
assert a == 42;//throws an AssertsionError when a is not 42
assert a == 42;//throws an AssertionError when a is not 42
assert a == 42 : "Error message"; //throws an AssertionError
assert a == 42 : "Error message"; //throws an AssertionError
//when a is not 42 with "Error message" for the message
//when a is not 42 with "Error message" for the message
//the error message can be any non-void expression
}</lang>
}</lang>

=={{header|Python}}==
<lang python>a = 5
#...input or change a here
assert a == 42 # throws an AssertionError when a is not 42
assert a == 42, "Error message" # throws an AssertionError
# when a is not 42 with "Error message" for the message
# the error message can be any expression</lang>

Revision as of 05:36, 4 February 2009

Task
Assertions
You are encouraged to solve this task according to the task description, using any language you may know.

Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point.

Show an assertion in your language by asserting that an integer variable is equal to 42.

Java

<lang java5>public static void main(String[] args){

  int a;
  //...input or change a here
  assert a == 42;//throws an AssertionError when a is not 42
  assert a == 42 : "Error message"; //throws an AssertionError 
         //when a is not 42 with "Error message" for the message
         //the error message can be any non-void expression

}</lang>

Python

<lang python>a = 5

  1. ...input or change a here

assert a == 42 # throws an AssertionError when a is not 42 assert a == 42, "Error message" # throws an AssertionError

      # when a is not 42 with "Error message" for the message
      # the error message can be any expression</lang>