๐Ÿ‘พ CS

[C++] noexcept Keyword

Mu Gyum 2023. 10. 17. 22:14

์ €๋ฒˆ์— ์ •๋ฆฌํ–ˆ๋˜ friend, explicit์— ์ด์–ด noexcept๋ผ๋Š” ์ƒˆ๋กœ์šด ํ‚ค์›Œ๋“œ์— ๋Œ€ํ•ด์„œ ์ •๋ฆฌํ•ด๋ณด๋ ค ํ•ฉ๋‹ˆ๋‹ค.

 

noexcept์€ ์–ด๋–ค ์˜๋ฏธ๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ๋ƒ,,, ๋ง ๊ทธ๋Œ€๋กœ ํ•จ๊ป˜ ์ž‘์„ฑ๋œ ํ•จ์ˆ˜์—์„œ ์˜ˆ์™ธ๋ฅผ ๋ฐœ์ƒ์‹œํ‚ค์ง€ ์•Š๊ฒ ๋‹ค๋Š” ๋œป์„ ๊ฐ€์ง€๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค.

 

ํ•ด๋‹น ํ‚ค์›Œ๋“œ๋ฅผ ์‚ฌ์šฉํ–ˆ์„ ๋•Œ ์ด์ ์€

1. ์œ ์ €์™€ ์ปดํŒŒ์ผ๋Ÿฌ์—๊ฒŒ ํžŒํŠธ๋ฅผ ์ค„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

2. ์ฝ”๋“œ๋ฅผ ๊ฐ„๊ฒฐํ•˜๊ฒŒ ๋งŒ๋“ค ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

3. ์ปดํŒŒ์ผ๋Ÿฌ ์ตœ์ ํ™”๋ฅผ ๊ฐ€๋Šฅํ•˜๊ฒŒ ๋งŒ๋“ค์–ด์ค๋‹ˆ๋‹ค. 

 

์˜ˆ์ œ์™€ ํ•จ๊ป˜ ๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

#include <iostream>
#include <stdexcept>
using namespace std;

int funcA() noexcept {
    // ...e
    return 0;
}

int main() {

    try {
        funcA();
    }catch (char c) {
      std::cout << "Catch char!" << std::endl;
    } catch (...) {
        std::cout << "Default exception catch!" << std::endl;
    }
    std::cout << "Program ends without exception" << std::endl;

    return 0;
}

funcA์—์„œ ์—๋Ÿฌ๋ฅผ ๋˜์งˆ ์ˆ˜๋Š” ์—†์ง€๋งŒ ์ •์ƒ์ ์œผ๋กœ ์ž‘๋™๋˜๋Š” ๋ชจ์Šต์„ ๋ณผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

๊ทธ๋Ÿฐ๋ฐ ๋งŒ์•ฝ noexception ํ‚ค์›Œ๋“œ๋ฅผ ์‚ฌ์šฉํ–ˆ๋Š”๋ฐ Exception์„ throwํ•˜๋ฉด ๋ฐœ์ƒํ•˜๋ฉด ์–ด๋–ป๊ฒŒ ๋ ๊นŒ์š”

 

#include <iostream>
#include <stdexcept>
using namespace std;

int funcA() noexcept {
    // ...
    throw runtime_error("Exception!");
    return 0;
}

int main() {

    try {
        funcA();
    }catch (char c) {
      std::cout << "Catch char!" << std::endl;
    } catch (...) {
        std::cout << "Default exception catch!" << std::endl;
    }
    std::cout << "Program ends without exception" << std::endl;

    return 0;
}

 

libc++abi: terminating due to uncaught exception of type std::runtime_error: Exception!

ํ•ด๋‹น ์˜ค๋ฅ˜๋Š” ์˜ˆ์™ธ๊ฐ€ ์ฒ˜๋ฆฌ๋˜์ง€ ์•Š๊ณ  ํ”„๋กœ๊ทธ๋žจ์ด ๋น„์ •์ƒ์ ์œผ๋กœ ์ข…๋ฃŒ๋˜์—ˆ๊ธฐ ๋•Œ๋ฌธ์— ๋œฌ๋‹ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค.

 

noexception ๋•Œ๋ฌธ์— ์˜ˆ์™ธ๊ฐ€ ์ œ๋Œ€๋กœ ์ฒ˜๋ฆฌ๋˜์ง€ ์•Š์€ ๊ฒƒ ๊ฐ™๋„ค์š”.