'예외 처리 구문'에 해당되는 글 1건

  1. 2020.12.16 예외 처리

예외 처리

C++ 2020. 12. 16. 23:22

예외(Exception)

- 프로그램이 동작하는 과정에서 발생하는 예상치 못한 오류를 의미

- 발생할 가능성이 높은 오류에 대해서 예외 처리를 할 수 있도록 해줌

 

예외 처리 구문

- try - catch 구문을 이용해서 예외 처리를 수행할 수 있도록 함

- try : 특정한 코드 블록에서 예외가 발생할 수 있음을 명시

- catch : 발생한 예외에 대해서 핸들러가 특정한 내용을 처리

- throw : try 구문에서 발생한 오류를 전달

 

* 예외 발생 예제

#include <iostream>
#include <string>
#include <stdio.h>

using namespace std;

int main(void) {
    int a = 7, b = 0;
    cout << a / b << 'n'; // 나누기 연산은 0으로 나눌수 없음, 오류 발생
    system("pause");
    return 0;
}

 

* 예외 처리 예제

#include <iostream>
#include <string>
#include <stdio.h>

using namespace std;

int main(void) {
    int a = 7, b = 0;
    try {
        if (b == 0) {
            throw "0으로 나눌 수 없음";
        }
        cout << a / b << 'n';
    } catch (const char* str) {
        cout << str << '\n';
    }
    system("pause");
}

 

* 클래스에서의 예외 처리

#include <iostream>
#include <string>
#include <stdio.h>

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 << "0으로 나눌 수 없음.\n";
        }
    }
    system("pause");
}

'C++' 카테고리의 다른 글

소켓 프로그래밍 함수와 Winsock2  (0) 2020.12.17
소켓 프로그래밍의 개요  (0) 2020.12.17
STL 연관 컨테이너  (0) 2020.12.16
STL 시퀀스 컨테이너  (0) 2020.12.16
STL 컨테이너 어댑터  (0) 2020.12.16
Posted by khon98
,