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

后端 未结 5 862
别那么骄傲
别那么骄傲 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:33

    I know this is old, but here is a pure syntax solution, which I think is the proper way to go:

    try {
        // Protected-block
        try {
            // Else-block
        } catch (e) {
            // Else-handler-block
        }
    } catch(e) {
        // Handler-block
    } finally {
        // Final-block
    }
    

    The code in Protected-block is executed. If the code throws an error, Handler-block is executed; If no error is thrown, Else-block is executed.

    No matter what happened previously, Final-block is executed once the code block is complete and any thrown errors handled. Even if there’s an error in Handler-block or Else-block, the code in Final-block is still run.

    If an error is thrown in the Else-block it is not handled by the Handler-block but instead by the Else-handler-block

    And if you know that the Else-block will not throw:

    try {
        // Protected-block
        // Else-block
    } catch(e) {
        // Handler-block
    } finally {
        // Final-block
    }
    

    Moral of the story, don't be afraid to indent ;)

    Note: this works only if the Else-handler-block never throws.

提交回复
热议问题