14.1 예외처리의 기본
예외처리의 기본
어떤 함수에서 정상적으로 작동했을 때는 그 값을, 안됐을 때는 return -1 이라던지 이렇게 할 수 있지만 -1이 return되면 잘못됐다는 것을 알고있어야 하기 때문에 불편하다. bool 형태로 받을 수도 있다. Throw,try,catch는 이것들을 대체할려고 하는 것은 아니다. 예외처리를 하면 약간 느려지는 경우가 있다. 퍼포먼스가 중요한 경우에는 넣지 않는 경우도 있다.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
// try, catch, throw
double x;
cin >> x;
try
{
if ( x < 0.0 ) throw std::string("Negative input"); // throw에 넣을때는 캐스팅이 엄격함. 정확한 타입을 입력해야함.
cout << std::sqrt(x) << "\n";
}
catch ( std::string error_message )
{
//do something to respond
cout << error_message << "\n";
}
return 0;
}
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
try
{
// something happend
throw -1;
// throw "My error message" -> const char *
// throw std::string("My error message") -> std::string
// throw -1.0; 하면 아무데서도 받아주지 않아서 런타임에러가 뜬다. 캐스팅을 자동으로 해주지 않는다.
}
catch ( int x )
{
cout << "Catch integer" << "\n";
}
catch (std::string error_message)
{
cout << error_message << "\n";
}
catch (const char * error_message)
{
cout << "Char * " << error_message << "\n";
}
return 0;
}