# 【Assert】

`assert()` 必須指被用來檢測內部錯誤，意思就是用來測試或 debug，並且用來檢測不變量（不該被改變的常數等）。

以下的例子是 `num` 這個變數必須只為 `0`，在我們的預想之中它得是個常數不該被更改，所以為了確認我們沒有忽略它被改變的情況，這裡加上 `assert()` 在 `num` 被改變時使程式強制中止。

```solidity
pragma solidity ^0.8.11;

contract error {
    function testAssert(uint _i) public view {
        assert(_i == 0);
    }
}
```

Asserted 會被觸發的情況及性質如下：

* `assert(X)` 當X 之值為`false`
* 踩到了超出範圍的 index
* 除以0或取除以0之餘數（5/0 or 23%0）
* 位元移動運算（Byteshifting）時位移量為負
* 轉換負值或過大的數字成`enum`資料結構

Assert 和 Require的比較

* 當`require`面對Revert operation(0xfd) 時會送回剩餘的gas
* 當`assert`面對Invalid operation(0xfe) 時會消耗全部的gas
* Assert 用於檢測完全不該在合約裡出現的情況
* Require 用來檢測使用者的輸入等錯誤情況


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://chihaolu.gitbook.io/all-in-one-solidity/part-ii-medium/chapter-9-yi-chang-chu-li-handling-exception/assert.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
