1
2
3
4
5
6
7
8
9
|
public
class
AssertExampleOne{
public
AssertExampleOne(){}
public
static
void
main(String args[]){
int
x=
10
;
System.out.println(
"Testing Assertion that x==100"
);
assert
x==
100
:
"Out assertion failed!"
;
System.out.println(
"Test passed!"
);
}
}
|
1
2
3
4
5
6
7
8
9
10
|
public
class
AssertExampleTwo{
public
static
void
main(String args[]){
boolean
isEnable=
false
;
//...
assert
isEnable=
true
;
if
(isEnable==
false
){
throw
newRuntimeException(
"Assertion should be enable!"
);
}
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
#include<assert.h>
#include<stdio.h>
#include<stdlib.h>
struct
ITEM
{
int
key;
int
value;
};
/*add item to list,make sure list is not null*/
void
additem(
struct
ITEM* itemptr)
{
assert
(itemptr!=NULL);
/*additemtolist*/
}
int
main(
void
)
{
additem(NULL);
return
0;
}
|
1
2
3
4
5
6
|
#defineassert(expr)\
((expr)\
?__ASSERT_VOID_CAST(0)\
:__assert_fail(__STRING(expr),__FILE__,__LINE__,__ASSERT_FUNCTION))
/*DefinedInGlibc2.15*/
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
int
main(
void
){
FILE
* fp;
fp=
fopen
(
"test.txt"
,
"w"
);
//以可寫的方式打開一個文件,若是不存在就建立一個同名文件
assert
(fp);
//因此這裏不會出錯
fclose
(fp);
fp=
fopen
(
"noexitfile.txt"
,
"r"
);
//以只讀的方式打開一個文件,若是不存在就打開文件失敗
assert
(fp);
//因此這裏出錯
fclose
(fp);
//程序永遠都執行不到這裏來
return
0;
}
|