---
# System prepended metadata

title: OOP - Exception Handling
tags: [C++=>OOP]

---

# OOP - Exception Handling



## :memo:  介紹
---
例外處理為C++, Python, Java...等等的語言都擁有的偵錯函式，其目的是偵錯。首先在try裡放入欲偵測的判斷，如果try內的判斷成立，則會throw出一個變數給catch接(可以是任何變數)，catch再執行完裡面的程式碼，若try裡面的判斷皆不成立，則代表要偵測的程式碼都是正常運行的。




## :memo: Code Segments
---

接下來可以試試看直接執行下面的例子

- Example 
```cpp
#include <iostream>
using namespace std;

void sampleF(int test);

int main(){
    int a = 0; cin >> a;
    
    try{
        cout << "Testing if there's error... " << endl;
        sampleF(a);
        cout << "Nope!" << endl;
    } catch(int){
        cout << "Error, the number is too small" << endl;
    }
    
    return 0;
}

// C++17 後已不支援在函式後面加 throw(int)
void sampleF(int test) throw(int) {
    if (test < 100){
        throw 50;
    }
}

/*
**  輸入: 10
**  印出:
**  Testing if there's error...
**  Error, the number is too small

**  輸入: 1000
**  印出:
**  Testing if there's error...
**  Nope!
*/

```


- Example 
```cpp
#include <iostream>
using namespace std;

int main(){
    int time = 50;
    try {
        cout << "Trying ...." << endl;
        if (time > 25) {
            // throw 完後就不執行下面的程式碼
            throw time;
        }
        cout << " Done! " << endl;
    } catch (int thrownValue) {
        cout << "Exception thrown with time " << thrownValue << endl;
    } catch (char c){
        cout << "this won't work, because there's no character being catched "<<endl;
    }
    cout << "End..." << endl;
    return 0;
}

/*
**  印出:
**  Trying ....
**  Exception thrown with time 50
**  End...
*/

```

>[name=罐子]
###### tags: `C++=>OOP`
