【问题标题】:Break on try/throw/catch打破尝试/投掷/接球
【发布时间】:2016-05-11 03:39:51
【问题描述】:

我正在尝试使用 try/throw/catch 在 console.log() 中以正确的方式显示错误。如果我使用此代码:

var add = function ( a, b ) {
    try {
        if ( typeof a !== 'number' || typeof b !== 'number' ) throw {
            name: 'TypeError!\n',
            message: 'You must enter two numbers'
        }
    } catch ( e ) {
        console.log( e.name + e.message );
    }
    return a + b;
}
console.log( add( 3, undefined ) );

我的控制台显示:

TypeError!
You must use two numbers as parameters
NaN

我怎样才能中断函数以在控制台日志中只得到错误而不是结果,在这种情况下是 NaN?我尝试在 catch 内的控制台日志后使用 break 语句,但控制台说:

Uncaught SyntaxError: Illegal break statement

【问题讨论】:

    标签: javascript try-catch throw


    【解决方案1】:

    你只能在循环中使用break,你应该使用return从函数中返回。你也可以选择不捕获异常,让它流回调用者。

    一个例子:

    var add = function ( a, b ) {
        if ( typeof a !== 'number' || typeof b !== 'number' ) throw {
            name: 'TypeError!\n',
            message: 'You must enter two numbers'
        }
        return a + b;
    }
    
    try {
        console.log( add( 3, undefined ) );
    } catch ( e ) {
        console.log( e.name + e.message );
    }
    

    【讨论】:

    • 好吧,对不起!很明显为什么我不能使用 break 语句。但是,如果我在捕获控制台返回Type Error! You must use two numbers as parameters undefined 中使用return,那么在控制台日志上打印也未定义,因为return 语句总是返回一个值。我只想打印错误而不打印其他内容。
    • 而且,我如何选择不捕获异常?我必须总是在尝试后使用 catch 或 finally 。不用我吗?
    • 不要在那个函数中使用 try 和 catch,你可以将 throw 留在这个函数中,但是将 try 和 catch 放在另一个函数中。如果仍然感到困惑,请参阅示例。
    猜你喜欢
    • 2011-03-13
    • 2017-10-12
    • 2023-03-16
    • 2011-04-14
    • 2016-07-02
    • 2011-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多