Difference between revisions of "Assertions"
From Suhrid.net Wiki
Jump to navigationJump to searchLine 2: | Line 2: | ||
* Assertions allow the testing of assumptions about a program. | * Assertions allow the testing of assumptions about a program. | ||
− | * Using assertions allow easy detection of bugs during development without writing exception handlers etc. | + | * Using assertions allow easy detection of bugs during development without writing exception handlers etc. |
* We "assert" that something will be true at some point in the code. If it is, code keeps running, if it is false, an AssertionError will be thrown. | * We "assert" that something will be true at some point in the code. If it is, code keeps running, if it is false, an AssertionError will be thrown. | ||
Line 28: | Line 28: | ||
* Second version of assert takes a second expression which should return string. This string is added to the stack trace. | * Second version of assert takes a second expression which should return string. This string is added to the stack trace. | ||
− | + | ||
+ | <syntaxhighlight lang="java5"> | ||
+ | |||
+ | private static void processAge2(int age) { | ||
+ | assert age > 0 : "Age is negative"; | ||
+ | System.out.println("Processing age ..."); | ||
+ | } | ||
+ | |||
+ | </syntaxhighlight> | ||
[[Category:OCPJP]] | [[Category:OCPJP]] |
Revision as of 01:52, 20 July 2011
Introduction
- Assertions allow the testing of assumptions about a program.
- Using assertions allow easy detection of bugs during development without writing exception handlers etc.
- We "assert" that something will be true at some point in the code. If it is, code keeps running, if it is false, an AssertionError will be thrown.
Example:
//Without assertions
private static void processAge1(int age) {
if(age > 0) {
System.out.println("Processing age ...");
} else {
System.out.println("Age < 0 !");
}
}
//With assertions
private static void processAge2(int age) {
assert age > 0;
System.out.println("Processing age ...");
}
- Second version of assert takes a second expression which should return string. This string is added to the stack trace.
private static void processAge2(int age) {
assert age > 0 : "Age is negative";
System.out.println("Processing age ...");
}