C ++-有关引发异常的几个问题 [英] C++ - A few questions about throwing exceptions

查看:111
本文介绍了C ++-有关引发异常的几个问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于在C ++中引发异常,我有几个问题。
根据我对它们的了解...

I've got a few questions about throwing exceptions in C++. From what I know about them...

可以从main()函数中引发异常。可以在main()函数中引发异常的任何代码块都应按如下所示的try和catch语句

An exception can be thrown from within the main() function. Any block of code that can throw an exception in the main() function should be surrounded by try and catch statements as follows

    void foo(//args) {
     if (...) {
      throw "Error reached";
     } ...

    int main() {
     ...
     try {
      //Code that can throw an excpetion
     } catch(const char* msg) (
      cerr << msg << endl;
     } 
     ...
    }

在上面的示例中,为什么catch的参数为const char *。C ++不允许使用字符串吗? ,是否可能引发不是const char *的异常(例如int或char?)?

是否会引发

在foo中出现异常,终止foo函数吗?在某些情况下,您可以将try和catch语句放在与throw相同的函数中?

抱歉,这是基本问题。
谢谢。

Sorry if these are basic questions. Thanks SO

推荐答案


为什么catch的参数是const char *

why is the argument to the catch a const char *

您抛出了字符串文字,该文字会衰减为 const ch ar * 。简而言之,就是抓住了。

Because you threw string literal which decays to const char*. In short, you catch what you throw.


C ++是否不允许使用字符串?

Doesn't C++ allow for strings?

可以,但是要捕获字符串,您需要将字符串放在首位。

It does, but to catch string, you need to throw string in first place.


是否有可能抛出不是const char *的异常,

is it possible to throw an exception that isn't a const char *,

您几乎可以扔任何东西。抛出特殊异常类(如 std :: exception 并从其派生)是一个好主意。

You can throw literally anything. It is a good idea to throw special exception classes, like std::exception and derived from it.


在foo中引发异常,终止foo函数吗?

Does throwing an exception in foo, terminate the foo function?

是的。


在某些情况下,可以将try和catch语句置于与throw相同的功能中吗?

Are there cases where you could put the try and catch statements in the same function as the throw?

如果需要,您可以这样做。

If you want, you can do that. There are not much cases where doing it is a good idea.

看来,您需要获得一本好书并阅读有关异常的章节。同时,此超级常见问题解答可能会帮助您/

It looks like you need to get a good book and read chapter about exceptions. In the meantime this super-FAQ entry might help you/

这篇关于C ++-有关引发异常的几个问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆