반응형
예외처리
exception은 예상치 못한 오류를 의미한다. c++은 발생 가능성이 높은 오류들을 예외처리하는 기능을 제공한다.
try : 예외 발생가능 인지.
catch : 특정 내용 처리
throw : 발생 오류 전달. 예외 발생시 가장 가까운 catch문으로 이동한다.
예를 들면
int main(){
int a = 7, b = 0;
cout << a/b << '\n';
return 0;
}
이런 경우에 관해서는 아래와 같이 예외처리할 수 있다.
#include<iostream>
using namespace std;
int main(){
int a = 7, b = 0;
try{
if(b == 0){
// if절 만족시 throw를 통해 바로 catch 구분으로 이동. parameter로 throw 뒤를 준다.
throw "can't divide by 0";
}
cout << a / b << '\n';
}
catch(const char* str){ // throw를 받는다.
cout << str << '\n';
}
return 0;
}
출력은
can't divide by 0
사견이지만, 이런 방식이면 C언어에서의 goto문으로 try-catch 방법을 모방할 수 있지 않을까 싶다. 물론 이런 방법 외의 자동적인 예외처리 기능은 구현하기 어렵겠지만...
클래스에서는 아래와 같이 예외처리 할 수 있다.
#include<iostream>
using namespace std;
template <typename T>
class Data{
private:
T data;
public:
Data(T data) : data(data){ }
T getData() { return data; }
Data<T> operator /(const Data<T> &other){ // 연산자 오버로딩
if(other.data == 0){
throw 0;
}
return Data(data / other.data);
}
};
int main(void){
try{
Data<int> a(7);
Data<int> b(0);
Data<int> result = a/b;
cout << result.getData() << '\n';
}
catch(int e){
if(e == 0){
cout << "can't divide by 0\n";
}
}
}
출력은
can't divide by 0
참고자료
https://tcpschool.com/cpp/cpp_io_streamBuffer
https://newmkka.tistory.com/78
https://modoocode.com/230
반응형
'Programming Tools > C++' 카테고리의 다른 글
[C++] Const 총 정리 - 2 (0) | 2021.06.13 |
---|---|
[C++] Const 총 정리 - 1 (0) | 2021.06.12 |
[코드 중심 C++] - STL(Standard Template Library) (0) | 2021.05.20 |
[코드 중심 C++] - 스마트 포인터(Smart Pointer : unique_ptr, share_ptr, weak_ptr) (0) | 2021.05.19 |
[코드 중심 C++] - 일반화, 탬플릿, 명시적 특수화, 암시적 구체화 (Generic Programming, Template, Explicit Specialization, Implicit instantiation) (0) | 2021.05.17 |