royqh1979 / RedPanda-CPP

A light-weight C/C++ IDE based on Qt
GNU General Public License v3.0
953 stars 103 forks source link

建议加入对 函数 try 块 的支持 #317

Closed West-Pavilion closed 5 months ago

West-Pavilion commented 5 months ago

建议加入对 函数 try 块 的支持

在 C++ 中,可以使用 try - catch 块将整个函数体包围起来,这个特性主要是为了捕获成员函数的 成员初始化器列表 中潜在的异常,但是这个语法在普通函数中也可以使用

在上述的用法中,函数的形参的作用域和生存期将会延长到最后一个 catch 子句 的末尾处

然而,当前版本的 小熊猫C++ 无法在这种用法的 catch 子句 中显示函数的形参的补全提示

请考虑如下的 C++ 代码:

#include <iostream>
#include <ctime>

/* 建议加入对 函数 try 块 的支持 */

class exception_member {
    int member_id = -1;
    public:
    /* 成员函数中的 函数 try 块(可以包含成员初始化器列表) */
        exception_member(int member_id) try : member_id(member_id){
            throw std::runtime_error("Construction failed");
        } catch (const std::logic_error& e) {
            /* 仅做演示,控制流不会到达此处 */
            /* 函数 try - catch 块中,函数声明中的形参(不包含块中声明的对象)的作用域和生存期会延续到
            * 最后一个 catch 子句 的结尾,因此在此处编辑器应显示 member_id 的补全提示 */
//          member
            std::cout << "logic_error throwed with member_id: " << member_id << std::endl;
        } catch (...) {
            /* 此处编辑器应显示 member_id 的补全提示 */
//          member
            std::cout << "failed to construct member_id: " << member_id << std::endl;
            std::cout << "exception catched" << std::endl;
        }
        int get_time() {
            return time(nullptr);
        }
};

class my_class {
    int time;
    public:
        my_class():time(exception_member{100}.get_time()) {};
};

/* 普通函数的 函数 try 块 */
int fib(int n) try {
    if(n <= 0) {
        throw std::invalid_argument("The input number is too large");
    }
    return (n == 1 || n == 2) ? 1 : fib(n - 1) + fib(n - 2);
} catch (const std::exception& e){
    /* 此处应有 n 的补全提示 */
//  n
    std::cout << e.what() << ", this function can't calculate the result of fib(" << n << ")." << std::endl;
    return -1;
} catch ( ... ) {
    /* 此处应有 n 的补全提示 */
//  n
    std::cout << "n is still valid here with its value: " << n << std::endl;
    return -1;
}

int main() {
    try {
        my_class my_class_obj;
    } catch (const std::runtime_error& e) {
        std::cout << e.what() << std::endl;
    }
    std::cout << "current timestamp: " << std::time(nullptr) << std::endl;

    std::cout << "fib(-1) is invalid and will trigger the exception: " << fib(-1) << std::endl;
    std::cout << "fib(7) is valid with a result " << fib(7) << std::endl;
}

实际效果演示图:

屏幕截图(307)

屏幕截图(308)

下面是对应的测试代码:

建议加入对 函数 try 块 的支持.zip

royqh1979 commented 5 months ago

奇怪的语法知识又增加了……暂不打算支持