You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

十六进制转十进制程序异常抛出后输出不符合预期问题求助

解决十六进制转十进制异常时多余前缀输出的问题

问题原因

你的代码中,try块里先执行了前缀文本的输出操作,之后才调用hex2Dec函数。当输入非法十六进制数时,hex2Dec抛出异常,但此时前缀文本已经被打印到控制台,导致错误信息跟在后面,不符合仅输出错误信息的需求。

解决方案

调整代码执行顺序:先调用hex2Dec完成转换(触发异常检查),确认无异常后再输出完整的成功信息。这样异常抛出时,前缀文本不会被输出,直接进入catch块打印错误信息。

修改后的代码

#include <cctype>
#include <iostream>
#include <string>
#include <exception>

using namespace std;

// Converts a hex number as a string to decimal
int hex2Dec(const string& hex);
// Converts a hex character to a decimal value
int hexCharToDecimal(char ch);

//defining HexFormatException exception class
class HexFormatException: exception{
public:
    //overriding what method to return an error message
    const char* what() const noexcept override {
        return "Not a hex number";
    }
};

int main()
{
    // Prompt the user to enter a hex number as a string
    cout << "Enter a hex number: ";
    string hex;
    cin >> hex;
    //calling hex2dec method inside a try block
    try{
        // 先执行转换,触发异常检查
        int decimalValue = hex2Dec(hex);
        // 转换成功后再输出完整信息
        cout << "The decimal value for hex number " << hex << " is " << decimalValue
         << endl;
    }catch(HexFormatException& e){
        //in case if HexFormatException occur, printing error message.
        cout<<e.what()<<endl;
    }
    
    return 0;
}

int hex2Dec(const string& hex)
{
    int decimalValue = 0;
    for (unsigned i = 0; i < hex.size(); i++){
        //checking if current char is a digit or lower/upper case hex char
        if(isdigit(hex[i]) || (hex[i]>='A' && hex[i]<='F') || 
            (hex[i]>='a' && hex[i]<='f')){
            //valid
            decimalValue = decimalValue * 16 + hexCharToDecimal(hex[i]);
        }else{
            //if not valid, throwing HexFormatException
            throw HexFormatException();
        }
        
    }
    return decimalValue;
}

int hexCharToDecimal(char ch)
{
    ch = toupper(ch); // Change it to uppercase
    if ('A' <= ch && ch <= 'F')
        return 10 + ch - 'A';
    else // ch is '0', '1', ..., or '9'
        return ch - '0';
}

关键改动说明

  1. 调整执行顺序:在try块内先调用hex2Dec(hex)并将结果存入变量,这一步会先验证输入合法性,若非法直接抛出异常,不会执行后续的cout语句。
  2. 规范异常方法:修改what()方法为const char* what() const noexcept override,符合C++标准库中exception类的虚函数签名,避免潜在的未定义行为。

内容的提问来源于stack exchange,提问作者user20544996

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 03:10:14