Repetition and Exceptions๋?
์์ธ ํด๋์ค
ํด๋์ค์์์ ์์ธ ์ฒ๋ฆฌํ๋ ๋ฐฉ์์ ํ์ฅํ๊ณ ๊ด๋ฆฌํ๊ธฐ ํธํ๊ฒ ๋ง๋๋ ํด๋์ค
class Bureaucrat
{
public:
class GradeTooHighException : public std::exception
{
public:
const char *what() const throw()
{
return ("error");
}
};
**std::exception**์ C++ ํ์ค ๋ผ์ด๋ธ๋ฌ๋ฆฌ์์ ์ ๊ณตํ๋ ๊ธฐ๋ณธ ์์ธ ํด๋์ค
์์ ๊ฐ์ ํ์์ผ๋ก ์ ์ธํ ์ ์๋ค.
#include "Bureaucrat.hpp"
int main() {
try {
b.setGrade(0);
}
catch (std::exception &e) {
std::cout << "error : " << e.what() << std::endl;
}
}
throw๋ฅผ ์ฌ์ฉํ ๊ฒฝ์ฐ์๋ try, catch๋ฌธ๋ฒ์ ๊ฐ์ด ์ฌ์ฉํด์ค์ผํ๋ค.
throw๊ฐ ๋ฐ์์ด ๋๋ฉด ํด๋น return๊ฐ์ ๋์ง๊ฒ ๋๋๋ฐ ๊ทธ ๋์ ธ์ง return๊ฐ์ catch์์ ์ก์ง๋ชปํ๋ฉด
์์ ๊ฐ์ ํ์์ผ๋ก error๊ฐ ๋ฐ์์ด ๋๋ค.
๊ทธ๋์ throw๋ฅผ ์ฌ์ฉํ๋ค๋ฉด ์์ํจ์์์๋ catch๋ฅผ ์ฌ์ฉํด์ ๊ฐ์ ์ก์์ค์ผํ๋ค.
throw๊ฐ ๋ฐ์๋์๋ค๋ฉด ํด๋นํจ์๋ ์ฆ์ ์ข ๋ฃ๋๋ค.
( throw๊ฐ ๋ฐ์๋์๋ค๋ฉด ๊ฐ์ฅ ๊ฐ๊น์ด catch๋ฅผ ์ฐพ์์ ์ด๋ํ๋ค. )
class Bureaucrat
{
public:
class GradeTooHighException : public std::exception
{
public:
const char *what() const throw()
{
return ("error");
}
};
์์ ๋ชจ์ต์์ ์ ์ ์๋ฏ์ด std::exception ๊ฐ GradeTooHighException๋ฅผ ์์ํด์ฃผ๋ ํ์์ผ๋ก
๋ด์ฉ์ ๊ฐ๊ฐ ์งํ์ด ๋๋ค.
std::exception ์์ ์๋ what์ด๋ผ๋ ํจ์๋ฅผ GradeTooHighException ๊ฐ ์ฌ์ ์ํด์ฃผ๋ ํํ
C++ Chapter 14.3 : ์์ธ ํด๋์ค์ ์์
์น์ด๋จน๋ C ++ - <11. C++ ์์ ์์ธ ์ฒ๋ฆฌ>
'42seoul > projects' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[C++] casts (0) | 2024.03.13 |
---|---|
[CPP Module] 05 (0) | 2024.03.13 |
[C++] interfaces ( ์ธํฐํ์ด์ค ) (0) | 2023.09.13 |
[C++] abstract class (์ถ์ ํด๋์ค) (0) | 2023.09.13 |
[C++] ์๋ธ ํ์ ๋คํ์ฑ(Subtype Polymorphism) (0) | 2023.09.13 |