반응형
들어가기 전 try catch, throw과 exception,what을 공부하고 가자!
try catch, throw
https://wo-dbs.tistory.com/158
Try Catch, throw
→ 우리에게 익숙한 예외처리는 if문을 이용한 예외처리임. 하지만 if문을 보고 예외처리를 위한 코드인지 프로그램의 흐름을 구성하는 코드인지 쉽게 구분하지 못해서 가독성이 떨어짐. C++의
wo-dbs.tistory.com
exception,what
https://wo-dbs.tistory.com/159
exception, what
→ if-else문을 통해 예외를 인지하게 한 후 직접 throw를 던졌었지만 문제가 생기면 std::exception 클래스를 통해 시스템 상 내부에서 알아서 발생한 예외를 throw 한다. 예외(exception)은 프로그램 실행
wo-dbs.tistory.com
try catch문을 사용하고 exception이 나온다.
이제 천천히 문제를 풀어보자
- Bureaucrat.hpp
- 변함없는 이름 → const std::string name;
- 등급 → int grade;
- 등급에서 1과 150사이가 아니면 예외를 던져야한다고 함.
- 예외에는 GradeTooHighException, GradeTooLowException 2가지가 있다.
- getName() 및 getGrade() 만들기
- 관료 등급을 높이거나 낮추는 두 개의 구성원 함수 만들기 → downGrade, upGrade
#ifndef BUREAUCRAT_HPP
# define BUREAUCRAT_HPP
#include <iostream>
class Bureaucrat{
private:
const std::string name;
int grade;
public:
Bureaucrat(void);
Bureaucrat(std::string name, int grade);
Bureaucrat(Bureaucrat const &bureaucrat);
Bureaucrat &operator=(Bureaucrat const &bureaucrat);
~Bureaucrat(void);
std::string getName(void) const;
int getGrade(void) const;
void upGrade(void);
void downGrade(void);
class GradeTooLowException : public std::exception
{
public:
const char *what(void) const throw();
};
class GradeTooHighException : public std::exception
{
public:
const char *what(void) const throw();
};
};
std::ostream &operator<<(std::ostream &out, const Bureaucrat &bureaucrat);
# endif
main.cpp
#include "Bureaucrat.hpp"
int main()
{
try
{
Bureaucrat basic;
std::cout << basic;
}
catch (std::exception &e)
{
std::cout << e.what();
}
try
{
Bureaucrat normal("A", 75);
std::cout << normal;
}
catch (std::exception &e)
{
std::cout << e.what();
}
try
{
Bureaucrat high("A", 151);
std::cout << high;
}
catch (std::exception &e)
{
std::cout << e.what();
}
try
{
Bureaucrat low("A", 0);
std::cout << low;
}
catch (std::exception &e)
{
std::cout << e.what();
}
return 0;
}
반응형
'42Seoul > CPP Module 05' 카테고리의 다른 글
ex03 (0) | 2024.01.26 |
---|---|
ex02 (2) | 2024.01.26 |
ex01 (0) | 2024.01.26 |