C++ 异常处理C++_xcode
以下代码在Visual Studio 2010中完全可以引发异常:C++ 异常处理C++_xcode,c++,xcode,exception-handling,C++,Xcode,Exception Handling,以下代码在Visual Studio 2010中完全可以引发异常: #include <iostream> #include <cmath> using namespace std; int perfectSquare(double sq, int nu); int main() { double num; double sq
#include <iostream>
#include <cmath>
using namespace std;
int perfectSquare(double sq, int nu);
int main()
{
double num;
double squareRoot;
int perfectSq;
cout << "Enter the a number: ";
cin >> num;
try
{
squareRoot = sqrt(num);
perfectSq = perfectSquare(squareRoot, num);
cout << "The square root is: " << perfectSq << endl;
}
catch(char * exceptionString)
{
cout << exceptionString;
}
cout << "BYE." << endl;
// system("PAUSE");
return 0;
}
int perfectSquare(double sq, int nu)
{
int temp = sq;
if (sq != temp) //clever test; if square root IS NOT an INT
{
throw "not a perfect square.\n";
}
else
{
return sq;
}
}
#包括
#包括
使用名称空间std;
int perfectSquare(双sq,int nu);
int main()
{
双数;
双平方根;
int perfectSq;
cout>num;
尝试
{
平方根=sqrt(num);
perfectSq=perfectSquare(平方根,num);
cout您抛出的是一个字符串文本,在XCode中它似乎是一个const char*
,而不是char*
您实际上没有抛出char*
,而是抛出了一个const char*
。将异常捕获更改为
catch(const char * exceptionString)
它应该会起作用
<所有C++中的文字字符串都相当于指向一个常量字符串的指针,即“代码> const char *//>代码> ./p>快速修复。没有意识到这与V.S.的区别。谢谢。是的,它不应该在VisualStudio中工作。我喜欢Xcode更严格,因为忽略这个错误是错误的。实际上,字符串文字是类型为char[N]
,主要是出于历史原因。但您应该将其视为const char[N]
。因此,一方面,XCode的行为似乎不正确,但另一方面,无论如何,您应该捕获const char*
。