为什么我不能从我的抛出异常中打印出错误?

How come I don't can't print out error from my throw exception?

本文关键字:打印 出错 错误 抛出异常 不能 我的 为什么      更新时间:2023-10-16

我只是在学习抛出异常,我写了一个代码,但当我输入10000100000时,似乎无法打印出Error: too bigError:too large。我如何修复它,以便它可以打印出Error: too bigError:too large

#include<iostream>
#include<stdexcept>
using namespace std;
int main()
{
    int xxx;
    cout<<"please enter xxx:";
    cin>>xxx;
    if (xxx==1)
       cout<<"2";
    else if (xxx==10)
       cout<<"3";
    else if (xxx==100)
       cout<<"4";
    else if (xxx==1000)
       cout<<"5";
    else if (xxx==10000)
       throw "too big";
    else if (xxx==100000)
       throw "too large";
    return 0;
}

您似乎将太多的魔力归因于异常。

但从本质上讲,例外情况非常简单。基本上,这只是意味着一些低级代码创建了一个对象(通过throw),该对象最终会出现在一些高级代码中(通过catch)。

当没有catch时,异常会一直"下降"函数调用堆栈,并一直这样做,直到它"下降"main

当这种情况发生时,会发生一系列特殊事件。您可以使用相对先进的技术配置行为,但初学者真正需要知道的是,在这种情况下,您不能保证打印出任何错误消息。如果您希望异常导致错误消息,那么您必须自己编写必要的代码。

根据您的原始示例,该代码可能如下所示:

#include<iostream>
#include<stdexcept>
using namespace std;
int main()
{
    try
    {
        int xxx;
        cout<<"please enter xxx:";
        cin>>xxx;
        if (xxx==1)
           cout<<"2";
        else if (xxx==10)
           cout<<"3";
        else if (xxx==100)
           cout<<"4";
        else if (xxx==1000)
           cout<<"5";
        else if (xxx==10000)
           throw "too big";
        else if (xxx==100000)
           throw "too large";
        return 0;
    }
    catch (char const* exc)
    {
        cerr << exc << "n";
    }
}

然而,更令人困惑的是,与大多数其他有例外的语言不同,C++允许抛出任何类型的对象

让我们仔细看看这条线:

throw "too big";

CCD_ 11是类型为CCD_。C++允许您抛出这样一个对象。由于它可以转换为第一个元素的char const*,因此您甚至可以捕获它并将其他大小的文字字符串作为char const*

但这不是常见的做法。您应该抛出直接或间接从std::exception派生的对象。

这里是使用来自<stdexcept>报头的标准类std::runtime_error的示例。

(您的原始代码没有使用<stdexcept>中的任何内容。您可以在没有<stdexcept>的情况下完美地使用throw本身。)

#include <iostream>
#include <stdexcept>
#include <exception>
int main()
{
    try
    {
        int xxx;
        std::cout << "please enter xxx:";
        std::cin >> xxx;
        if (xxx==1)
           std::cout << "2";
        else if (xxx==10)
           std::cout << "3";
        else if (xxx==100)
           std::cout << "4";
        else if (xxx==1000)
           std::cout << "5";
        else if (xxx==10000)
           throw std::runtime_error("too big");
        else if (xxx == 100000)
           throw std::runtime_error("too large");
        return 0;
    }
    catch (std::exception const& exc)
    {
        std::cerr << exc.what() << "n";
    }
}

throw必须只写在try块中,所以将所有条件都写入try块,并通过立即在try框外捕获条件来执行操作

    try
{
condition
throw exception ;
}
catch exception
{
message or correction lines 
}