표준 예외 클래스 사용 (std::exception)
이 단계에서는 C++ 의 표준 예외 클래스에 대해 배우고, std::exception 계층 구조를 사용하여 다양한 유형의 런타임 오류를 처리하는 방법을 배웁니다. C++ 표준 라이브러리는 다양한 오류 시나리오를 다루는 미리 정의된 예외 클래스 집합을 제공합니다.
WebIDE 를 열고 ~/project 디렉토리에 standard_exceptions.cpp라는 새 파일을 만듭니다.
touch ~/project/standard_exceptions.cpp
standard_exceptions.cpp에 다음 코드를 추가합니다.
#include <iostream>
#include <stdexcept>
#include <limits>
double divideNumbers(double numerator, double denominator) {
// Check for division by zero using std::runtime_error
if (denominator == 0) {
throw std::runtime_error("Division by zero is not allowed!");
}
return numerator / denominator;
}
void checkArrayIndex(int* arr, int size, int index) {
// Check for out-of-range access using std::out_of_range
if (index < 0 || index >= size) {
throw std::out_of_range("Array index is out of bounds!");
}
std::cout << "Value at index " << index << ": " << arr[index] << std::endl;
}
int main() {
try {
// Demonstrate division by zero exception
std::cout << "Attempting division:" << std::endl;
double result = divideNumbers(10, 0);
}
catch (const std::runtime_error& e) {
std::cout << "Runtime Error: " << e.what() << std::endl;
}
try {
// Demonstrate array index out of range exception
int numbers[] = {1, 2, 3, 4, 5};
int arraySize = 5;
std::cout << "\nAccessing array elements:" << std::endl;
checkArrayIndex(numbers, arraySize, 2); // Valid index
checkArrayIndex(numbers, arraySize, 10); // Invalid index
}
catch (const std::out_of_range& e) {
std::cout << "Out of Range Error: " << e.what() << std::endl;
}
return 0;
}
표준 예외 클래스를 살펴보겠습니다.
-
std::exception:
- 모든 표준 예외의 기본 클래스입니다.
- 오류 설명을 얻기 위한 가상
what() 메서드를 제공합니다.
-
일반적인 파생 예외 클래스:
std::runtime_error: 프로그램 실행 중에만 감지할 수 있는 런타임 오류에 사용됩니다.
std::out_of_range: 인덱스 또는 반복자가 유효 범위를 벗어난 경우에 사용됩니다.
- 다른 일반적인 클래스에는
std::logic_error, std::invalid_argument 등이 있습니다.
프로그램을 컴파일하고 실행합니다.
g++ standard_exceptions.cpp -o standard_exceptions
./standard_exceptions
예시 출력:
Attempting division:
Runtime Error: Division by zero is not allowed!
Accessing array elements:
Value at index 2: 3
Out of Range Error: Array index is out of bounds!
표준 예외 클래스에 대한 주요 사항:
- 다양한 유형의 오류를 처리하는 구조화된 방법을 제공합니다.
- 각 예외 클래스는 특정 목적을 수행합니다.
what() 메서드는 설명적인 오류 메시지를 반환합니다.
- 보다 강력하고 유익한 오류 처리를 만드는 데 도움이 됩니다.