c++中的异常处理问题

starletsgo 2007-12-14 07:01:33
现在正在用异常处理,不过发现不少异常异常即使用try。。。catch(...)。。。也捕捉不到,我简化下我碰到的问题如下:
try
{
std::string str = "hello";
char ch = str[10]; // 越界了
}
catch(...)
{
// 异常处理
}
上面就不能捕捉到这个异常,运行时就直接跳出程序了,不知道这是什么问题,有没什么解决办法呢?

...全文
42 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
独孤过儿 2007-12-14
  • 打赏
  • 举报
回复
了解了,原来要自己控制throw异常才能捕捉到,多谢上面各位
=======================
不是要自己控制throw,而是需要有throw,才能catch。这个throw动作有可能是你自己来做的,也有可能是你用的模板库里面的类来

做的,总之是必须要有人来throw才行
starletsgo 2007-12-14
  • 打赏
  • 举报
回复
了解了, 原来要自己控制throw异常才能捕捉到,多谢上面各位
独孤过儿 2007-12-14
  • 打赏
  • 举报
回复
嘿嘿,我弄出来一种标准库的string抛出的异常,代码如下:

#include <iostream>
using namespace std;

int main()
{
try
{
string str = "hello";
cout<<str.at(10);
}
catch(...)
{
cout<<"I caught you! ^_^"<<endl;
}

return 0;
}
zenny_chen 2007-12-14
  • 打赏
  • 举报
回复
因为上面那个异常是属于操作系统捕获的异常,你不可能在你的程序中用try-catch去捕获。
C++不是Java,它是被计算机CPU直接运行的,而Java是通过虚拟机。所以虚拟机会帮你抛出诸如越界、空指针等异常。

对于用户程序,如果你想捕获异常,那么首先要抛出这个异常。如果你自己定义一个string,并定义某个异常,且在运行时抛出时,你才能捕获。


#include <iostream>
using namespace std;

#include <string.h>


class MyString
{
private:

const char *content;

public:

MyString(const char *s) : content(s)
{

}

char operator[] (int index)
{
if(content == NULL)
throw "Null Point!";
else if(index >= (int)strlen(content))
throw "index out of bound!";
else
return content[index];
}
};



void main(void)
{
MyString s1 = NULL;

try
{
char a = s1[0];
}
catch(const char *info)
{
cout << info << endl;

MyString s2 = "Hello";

try
{
char a = s2[10];
}
catch(const char *info2)
{
cout << info2 << endl;
}
}

}

独孤过儿 2007-12-14
  • 打赏
  • 举报
回复
这样用string根本不会抛出异常的
yebeans 2007-12-14
  • 打赏
  • 举报
回复
这个要看std::string对越界是不是抛出异常了,搞不好就是访问冲突。
独孤过儿 2007-12-14
  • 打赏
  • 举报
回复
#include <iostream>
using namespace std;

int main()
{
try
{
cout<<"In try block!"<<endl;
throw 1;
}
catch(...)
{
cout<<"I caught you! ^_^"<<endl;
}

return 0;
}

NND CSDN,为什么不支持非IE的浏览器!!!
独孤过儿 2007-12-14
  • 打赏
  • 举报
回复
乖乖,你这叫什么异常啊?o(∩_∩)o...哈哈

你看看这个能不能捕获:

#include <iostream>
using namespace std;


int main()
{
try
{
cout<<"In try block!"<<endl;
throw 1;
}
catch(...)
{
cout<<"I caught you! ^_^"<<endl;
}

return 0;
}

64,682

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧