Javascript try…catch…else…finally like Python, Java, Ruby, etc

后端 未结 5 857
别那么骄傲
别那么骄傲 2020-12-08 18:48

How can Javascript duplicate the four-part try-catch-else-finally execution model that other languages support?

A

5条回答
  •  天命终不由人
    2020-12-08 19:31

    I know the question is old and answers has already given but I think that my answer is the simplest to get an "else" in javascripts try-catch-block.

    var error = null;
    try {
        /*Protected-block*/
    } catch ( catchedError ) {
        error = catchedError; //necessary to make it available in finally-block
    } finally {
        if ( error ) {
            /*Handler-block*/
            /*e.g. console.log( 'error: ' + error.message );*/
        } else {
            /*Else-block*/
        }
        /*Final-block*/
    }
    

提交回复
热议问题