# assert的用法
## assert關鍵字語法很簡單,有兩種用法:
:::info
- assert <boolean表示式>
如果<boolean表示式>為true,則程式繼續執行。
如果為false,則程式丟擲AssertionError,並終止執行。
- assert <boolean表示式> : <錯誤資訊表示式>
如果<boolean表示式>為true,則程式繼續執行。
如果為false,則程式丟擲java.lang.AssertionError,並輸入<錯誤資訊表示式>。
- [參考網站](https://www.itread01.com/content/1547018948.html)
:::
java執行時 assert預設為關閉,必須要加-ea ,才會開啟
```java=
public class Test {
public double applyDiscount(double price) {
assert (price>0);
return price * 0.50;
}
public static void main(String[] args) {
Test t = new Test();
double newPrice = t.applyDiscount(Double.parseDouble(args[0]));
System.out.println("New Price : "+newPrice);
}
}
```
**在cmd執行下面指令,會得到下面結果**
![](https://i.imgur.com/74WTGxA.jpg)
**可以看到雖然 0並不大於0,但是因為沒有加-ea 參數,沒有開啟assert的情況下,程式依然可以正常運行**
**當加了-ea 參數,開啟assert時,就會跳出AssertionError**
---
**Question:**
```java=
class Engine{
double fueLevel;
Engine(int fueLevel){
this.fueLevel = fueLevel;
}
public void strat() {
//line n1
System.out.println("Started");
}
public void stop() {
System.out.println("Stopped");
}
}
```
Your design requires that:
- fuelLevel of Engine must be greater than zero when the start() method is invoked.
- The code must terminate if fuelLevel of Engine is less than or equal to zero.
## Which code fragment should be added at line n1 to express this invariant condition?
A. assert (fuelLevel) : "Terminating...";
B. assert (fuelLevel > 0) : System.out.println ("Impossible fuel");
**C. assert fuelLevel < 0: System.exit(0);**
D. assert fuelLevel > 0: "Impossible fuel" ;
- [x] **Answer: C**
:::warning
- 在一個if-else判斷中,如果我們程式是按照我們預想的執行,到最後我們需要停止程式,那麼我們使用System.exit(0)
- 而System.exit(1)一般放在catch塊中,當捕獲到異常,需要停止程式,我們使用System.exit(1)。這個status=1是用來表示這個程式是非正常退出。
:::
###### tags: `ocpjp`