Home >Web Front-end >JS Tutorial >How to use try catch instead of exit to end the program in JavaScript

How to use try catch instead of exit to end the program in JavaScript

不言
不言Original
2019-01-16 16:45:464252browse

exit can be used to forcefully terminate the program. However, there is no exit in How to use try catch instead of exit to end the program in JavaScript. In other languages, exit can be used to forcefully terminate the program, but it needs to be implemented in other ways in How to use try catch instead of exit to end the program in JavaScript. This article will introduce to you how to use try catch in How to use try catch instead of exit to end the program in JavaScript instead of exit to end the program.

How to use try catch instead of exit to end the program in JavaScript

#In How to use try catch instead of exit to end the program in JavaScript, to terminate a program like exit, you need to use a try catch statement.

When we want to terminate it in the try catch statement, we deliberately throw an exception and terminate the program, and the process after throwing the exception will not be executed.

Let’s take a look at the following program.

var flag = true;
try {
    if (flag) {
        throw new Error('终止程序并退出');
    }
    console.log('未执行的代码');
} catch (e) {
    console.log(e.message);
}

Execution result:

终止程序并退出

Through the above method, we can terminate the program.

This article ends here. For more exciting content, you can pay attention to other related column tutorials on the PHP Chinese website! ! !

The above is the detailed content of How to use try catch instead of exit to end the program in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn