Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/161.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在C++中进行错误处理和捕获 问题草图:_C++_Error Handling_Try Catch - Fatal编程技术网

如何在C++中进行错误处理和捕获 问题草图:

如何在C++中进行错误处理和捕获 问题草图:,c++,error-handling,try-catch,C++,Error Handling,Try Catch,这只是一些虚拟代码,用于显示它将发生在何处 问题: 这里的想法是,当发生不受欢迎的事情时,我们应该怎么做 来自Java,我们将抛出一个异常,并且不会执行返回,catch子句将相应地进行处理 但是这在C++中是如何工作的? 在上面的代码中,我返回x,因为它需要一个双精度&。但是这会破坏调用这个函数的代码。差不多,同样的道理也适用于java,除非你需要与传统/C++代码接口,否则抛出异常。 #include<stdexcept> double& ComplexNumber::o

这只是一些虚拟代码,用于显示它将发生在何处

问题: 这里的想法是,当发生不受欢迎的事情时,我们应该怎么做

来自Java,我们将抛出一个异常,并且不会执行返回,catch子句将相应地进行处理

<>但是这在C++中是如何工作的?
在上面的代码中,我返回x,因为它需要一个双精度&。但是这会破坏调用这个函数的代码。

差不多,同样的道理也适用于java,除非你需要与传统/C++代码接口,否则抛出异常。
#include<stdexcept>

double& ComplexNumber::operator[](const unsigned index){
   if(index>1){
       throw std::out_of_range("Index out of bounds");
   }

   if(index==0){
       return x;
   }
   return y;
}

<>你很好的开始,只要你花时间去学习这些经验法则背后的原因。

你也可以在C++中抛出一个异常。您可以抛出。只需使用异常。问题是什么?我们如何才能赶上EM?@ KoeMeMeNi尝试了一个catch块。抱歉,我对C++仍然是新的。正在尝试学习纠结…我更喜欢返回索引==0?x:y;是的,这是我可能会写的,但保持例子简单通常是好的。事实上,我过去曾将很多人与ternaries混淆:
#include<stdexcept>

double& ComplexNumber::operator[](const unsigned index){
   if(index>1){
       throw std::out_of_range("Index out of bounds");
   }

   if(index==0){
       return x;
   }
   return y;
}
try {
    // ComplexNumber cmplx defined somewhere
    cmplx[2];
} catch (std::out_of_range& ex) {
    // ...
    throw;
}