请教,这段代码可以转换为js代码吗?


#include <stdio.h>
#include <setjmp.h>
 
static jmp_buf buf;
 
void second(void) {
    printf("second\n");         // 打印
    longjmp(buf,1);             // 跳回setjmp的调用处 - 使得setjmp返回值为1
}
 
void first(void) {
    second();
    printf("first\n");          // 不可能执行到此行
}
 
int main() {  
    if ( ! setjmp(buf) ) {
        first();                // 进入此行前,setjmp返回0
    } else {                    // 当longjmp跳转回,setjmp返回1,因此进入此行
        printf("main\n");       // 打印
    }
 
    return 0;
}

运行结果
second
main

那个setjmp是一个异常机制,在js里直接手动抛出一个异常就是差不多的原理

let jmp_buf;
 
function second() {
    console.log("second\n");
    throw new Error(1)
}
 
function first() {
    second();
    console.log("first\n")
}

function main() {
    try{
        first()
    }catch(err) {
        console.log("main\n")
    }
}
main()

img

有帮助的话请点个采纳,谢谢