JavaScript try catch

 JavaScript try catch is a program that performs error filtering and judgment. It can judge whether there is an error in a piece of code. If an error occurs, stop the operation of the piece of code and return an error message. Generally speaking, during debugging try catch is quite easy to use, but it is not necessarily necessary for netizens, because netizens may not understand the error message at all, so designers must think clearly when using it. Try catch is a built-in function of JavaScript. It can be called at any time with additional installation. It can be used on the periphery of the entire program in a wide range, or simply used in conditional judgments or loops such as JavaScript if...else... , JavaScript for , JavaScript while .


JavaScript try catch basic syntax
try{
... put the code to be judged here...
}catch( err ){
... If an error message is thrown during try, execute the code here...
}

Simply writing a JavaScript try catch is like this. The first is to determine whether a certain code is wrong. If there is no error, the code in the catch will not be executed. Otherwise, document.write or alert is usually written in the catch. Wait for the display mode, output the error message, and let the designer deal with it appropriately.

JavaScript try catch example
<script type="text/javascript">
try{
 a(1);
}catch(err){
 document.write('Something wrong.');
}
</script>
The output of the above example: Something wrong.

Suppose we want to write a message that pops out of the dialog window and displays 1, we should write alert(1), but the designer writes a(1) with slippery hands. This is of course a very serious mistake. , After checking through try, skip the code of try and execute the code in catch instead, so the error message of Something wrong. is output. The usage is similar to JavaScript if...else... , the difference lies in if. .. else... You can only judge according to the rules set by the designer, you cannot judge whether the code throws an error message by yourself, JavaScript try catch is OK.

Post a Comment

0 Comments