C++ 为什么0在此异常处理代码中不被视为int? #包括 使用名称空间std; 无效tryl(内部测试){ 试一试{ 如果(测试) 投掷(测试); 其他的 抛出“它是一个字符串\n”; }捕获(int i){ cout
因为if(test)被计算为false(if(0)或if(false)),所以它跳转到else块,最后抛出异常“it is a string” 如果我理解正确,您问题的解决方案将是:C++ 为什么0在此异常处理代码中不被视为int? #包括 使用名称空间std; 无效tryl(内部测试){ 试一试{ 如果(测试) 投掷(测试); 其他的 抛出“它是一个字符串\n”; }捕获(int i){ cout,c++,exception,C++,Exception,因为if(test)被计算为false(if(0)或if(false)),所以它跳转到else块,最后抛出异常“it is a string” 如果我理解正确,您问题的解决方案将是: #include<iostream> using namespace std; void tryl(int test){ try{ if(test) throw(test); else throw "it is a st
#include<iostream>
using namespace std;
void tryl(int test){
try{
if(test)
throw(test);
else
throw "it is a string\n";
}catch(int i){
cout<<"exception caught int"<<"\n";
}
catch(char const *str){
cout<<"exception string"<<"\n";
}
}
int main(){
tryl(1);
tryl(2);
tryl(0);
}
#包括
使用名称空间std;
无效tryl(内部测试){
试一试{
if(isdigit(测试)){
投掷(测试);
}否则{
抛出“它是一个字符串\n”;
}
}捕获(int i){
cout已经对错误进行了注释。if(0)
为false。您应该使用。我建议您是否也要包含浮点数。让我问您,if(0)
的意思是什么?您是运行抛出(测试);
还是运行否则抛出“它是字符串”\n;
?这可以通过在调试器中运行程序并逐步执行来解决。是的,如果条件为false,则传递0,则将运行else,从而抛出字符串。感谢帮助,给定的测试参数都不会导致isdigit(test)
计算为true。该函数计算(通常)其参数的ASCII表示。
#include<iostream>
using namespace std;
void tryl(int test){
try{
if(isdigit(test)){
throw(test);
}else{
throw "it is a string\n";
}
}catch(int i){
cout<<"exception caught int"<<"\n";
}catch(char const *str){
cout<<"exception string"<<"\n";
}
}
int main(){
tryl(1);
tryl(2);
tryl(0);
}