Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

행복한 개구리

C++ Classes - Exceptions 본문

C++/공부내용

C++ Classes - Exceptions

HappyFrog 2022. 6. 30. 15:55


 

 

 

C++ 예외

C++ 코드를 실행할 때, 프로그래머의 실수로 인한 코딩 에러 또는 잘못된 입력, 이 외의 볼 수 없는 요소들로 인한 에러가 발생할 수 있습니다.

 

에러가 발생하면, C++는 보통 실행을 멈추고 에러메시지를 생성할 것입니다. 

 

 

 


C++ try와 catch

C++에서 예외를 다루는 세가지 키워드가 있습니다:  try throw  그리고  catch :

 

 try 선언은 실행되는 동안 당신이 에러를 위한 코드 블럭을 정의할 수 있습니다.

 

 throw  선언은 실행 중에 문제를 발견하면 예외를 배출하며 사용자 지정 에러를 생성할 수 있습니다.

 

 catch  선언은 try 블럭에서 에러가 발생하면 실행시킬 코드 블럭을 정의할 수 있습니다.

 

 try ,  catch 는 짝지어 사용합니다:

 

 

예시

try {
  // 시도할 코드 블럭
  throw exception; // 문제가 발생했을 때 예외 배출
}
catch () {
  // 에러를 다룰 코드 블럭
}

 

다음 예시를 봅시다:

 

 

예시

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
	try {
		int age = 15;
		if (age >= 18) {
			cout << "Access granted - you are old enough.";
		}
		else {
			throw (age);
		}
	}
	catch (int myNum) {
		cout << "Access denied - You must be at least 18 years old.\n";
		cout << "Age is: " << myNum;
	}
	return 0;
}

 

예시 설명

 try  블록을 사용하여 코드를 테스트합니다: 만약  age 가  18 보다 작으면 우리는 예외를  throw 하며  catch 블럭에서 다룰 것입니다.

 

 catch 블럭에서 우리는 에러를 포착하고 이것을 가지고 무언가를 할 수 있습니다.  catch 선언은 매개변수를 갖습니다: 우리 예시에서는  age 의 값을 출력하기 위한  int  변수( myNum )를 사용할 수 있습니다. (왜냐하면 우리가  try 블럭에서  int  타입인  age 를 배출했기 때문입니다.)

 

만약 에러가 발생하지 않는다면,  catch 블럭은 건너뛸 것입니다.

 

 

예시

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
	try {
		int age;
		cin >> age;
		if (age >= 18) {
			cout << "Access granted - you are old enough.";
		}
		else {
			throw (age);
		}
	}
	catch (int myNum) {
		cout << "Access denied - You must be at least 18 years old.\n";
		cout << "Age is: " << myNum;
	}
	return 0;
}

 

당신은 또한 목적에 의해 구성된 사용자 지정 에러코드처럼  throw 키워드를 참고 번호를 출력하는데 사용할 수 있습니다:

 

 

예시

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
	try {
		int age;
		cin >> age;
		if (age >= 18) {
			cout << "Access granted - you are old enough.";
		}
		else {
			throw 505;
		}
	}
	catch (int myNum) {
		cout << "Access denied - You must be at least 18 years old.\n";
		cout << "Error Number:  " << myNum;
	}
	return 0;
}

 

 

 


아무 타입의 예외 다루기 (...)

만약 당신이  try 블럭을 사용하는데  throw 의 타입을 모를 때, 당신은  catch 블럭 안에 마침표 세개(...)를 사용한 문법으로 어떤 타입의 예외든 잡아낼 수 있습니다:

 

 

예시

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
	try {
		int age;
		cin >> age;
		if (age >= 18) {
			cout << "Access granted - you are old enough.";
		}
		else {
			throw age;
		}
	}
	catch (...) {
		cout << "Access denied - You must be at least 18 years old.\n";
	}
	return 0;
}