亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

JavaScript Errors - throw, try, and catch

try statement tests code block for errors.

catch statement handles errors.

throw statement creates a custom error.

JavaScript Errors

When the JavaScript engine executes JavaScript code, various errors may occur.

may be a syntax error, usually a coding error or typo made by the programmer.

could be a spelling mistake or a missing feature in the language (possibly due to browser differences).

The error may be caused by incorrect output from the server or user.

Of course, it may also be due to many other unpredictable factors.

JavaScript throws errors

When an error occurs, when something goes wrong, the JavaScript engine usually stops and generates an error message.

The technical term to describe this situation is: JavaScript will throw an error.

JavaScript try and catch

try statements allow us to define blocks of code that are tested for errors when executed.

The catch statement allows us to define the code block that is executed when an error occurs in the try code block.

JavaScript statements try and catch appear in pairs.

Syntax

try {
//Run code here
} catch(err) {
//Handle errors here
}

Example:

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title>php中文網(wǎng)(php.cn)</title> 
<script type="text/javascript">
    function message()
    {
    try
    {
    adlert("Hello World!");
    }
    catch(err)
    {
    alert("錯啦!");
    }
    }
</script>
</head>
<body>
  <input type = "button" value = "點擊" onclick = "message()">
</body>
</html>

Throw Statement

The throw statement allows us to create custom errors.

The correct technical term is: create or throw an exception (exception).

If you use throw with try and catch, you can control the program flow and generate custom error messages.

Syntax

throw exception

Exception can be a JavaScript string, number, logical value or object.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php.cn</title>
<script>
function myFunction(){
try{ 
var x=document.getElementById("demo").value;
if(x=="")    throw "值為空";
if(isNaN(x)) throw "不是數(shù)字";
if(x>10)     throw "太大";
if(x<5)      throw "太小";
}
catch(err){
var y=document.getElementById("mess");
y.innerHTML="錯誤:" + err + "。";
}
}
</script>
</head>
<body>
<p>請輸出一個 50 到 100 之間的數(shù)字:</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">請輸入</button>
<p id="mess"></p>
</body>
</html>


Continuing Learning
||
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文網(wǎng)(php.cn)</title> <script type="text/javascript"> function message() { try { adlert("Hello World!"); } catch(err) { alert("錯啦!"); } } </script> </head> <body> <input type = "button" value = "點擊" onclick = "message()"> </body> </html>
submitReset Code