Javascript Errors

8 min read

The try statement lets you test a block of code for errors.

tryТайлбар нь алдааны кодын блокыг шалгах боломжийг олгодог.

The catch statement lets you handle the error.

catch мэдэгдэл нь алдааг зохицуулах боломжийг танд олгоно.

The throw statement lets you create custom errors.

throw мэдэгдэл нь захиалгат алдаа үүсгэх боломжийг танд олгоно.

The finally statement lets you execute code, after try and catch, regardless of the result.

finally  мэдэгдэл нь үр дүнг үл харгалзан кодыг гүйцэтгэх боломжийг олгоно.


Errors Will Happen! #

Алдаа гарах болно! #

When executing JavaScript code, different errors can occur.

JavaScript кодыг гүйцэтгэх үед өөр өөр алдаа гарч болзошгүй юм.

Errors can be coding errors made by the programmer, errors due to wrong input, and other unforeseeable things.

Алдаа нь програм зохиогчийн гаргасан кодчилол, буруу оруулсантай холбоотой алдаа болон урьдчилан таамаглах боломжгүй зүйлс байж болно.

Example Жишээ #

In this example we misspelled “alert” as “adddlert” to deliberately produce an error:

Энэ жишээнд бид санаатайгаар алдаа гаргахын тулд “анхааруулга” -г “adddlert” гэж буруу бичсэн байна:

<p id="demo"></p> <script> try { adddlert("Welcome guest!"); } catch(err) { document.getElementById("demo").innerHTML = err.message; } </script>

JavaScript catches adddlert as an error, and executes the catch code to handle it.

JavaScript нь adddlert-ийг алдаа болгоод барьж авах кодыг ажиллуулдаг.


JavaScript try and catch #

JavaScript оролдоод үзээрэй #

The try statement allows you to define a block of code to be tested for errors while it is being executed.

try хэллэг нь гүйцэтгэгдэж байх явцад алдааг шалгах кодын блокийг тодорхойлох боломжийг олгодог.

The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

catch мэдэгдэлд алдаа блок гарсан тохиолдолд гүйцэтгэх кодын блокыг тодорхойлох боломжийг олгодог.

The JavaScript statements try and catch come in pairs:

JavaScript-ийн мэдэгдлүүд try бас  catch хосоороо орж үзээрэй.

try { Block of code to try } catch(err) { Block of code to handle errors }

JavaScript Throws Errors #

JavaScript алдаа шиддэг #

When an error occurs, JavaScript will normally stop and generate an error message.

Алдаа гарсан тохиолдолд JavaScript нь зогсч, алдааны мэдэгдэл үүсгэдэг.

The technical term for this is: JavaScript will throw an exception (throw an error).

Үүний техникийн нэр томъёо нь: JavaScript нь үл хамаарах зүйл (алдаа гаргах) болно.

JavaScript will actually create an Error object with two properties: name and message.

JavaScript нь үнэндээ нэр, мессеж гэсэн хоёр шинж чанартай Error объектыг үүсгэх болно.


The throw Statement #

Шидэх мэдэгдэл #

The throw statement allows you to create a custom error.

throw мэдэгдэл нь захиалгат алдаа үүсгэх боломжийг олгодог.

Technically you can throw an exception (throw an error).

Техникийн хувьд та үл хамаарах зүйлийг хаяж болно (алдаа шидэх).

The exception can be a JavaScript String, a Number, a Boolean or an Object:

Үл хамаарах зүйл нь JavaScript String, Number, Boolean эсвэл Object байж болно:

throw "Too big"; // throw a text throw 500; // throw a number

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

Хэрэв та throw хамтдаа try catch програмын урсгалыг хянах, тохируулсан алдааны мэдэгдлийг үүсгэх боломжтой.


Input Validation Example #

Оролтыг баталгаажуулах жишээ #

This example examines input. If the value is wrong, an exception (err) is thrown.

Энэ жишээнд оролтыг судалж үзсэн болно. Хэрэв утга буруу байвал онцгой тохиолдол (алдаатай) хаягдана.

The exception (err) is caught by the catch statement and a custom error message is displayed:

Үл хамаарах зүйл (err) нь catch мэдэгдэлд баригдах бөгөөд гаалийн алдааны мэдэгдэл гарч ирнэ.

<!DOCTYPE html> <html> <body> <p>Please input a number between 5 and 10:</p> <input id="demo" type="text"> <button type="button" onclick="myFunction()">Test Input</button> <p id="p01"></p> <script> function myFunction() { var message, x; message = document.getElementById("p01"); message.innerHTML = ""; x = document.getElementById("demo").value; try { if(x == "") throw "empty"; if(isNaN(x)) throw "not a number"; x = Number(x); if(x < 5) throw "too low"; if(x > 10) throw "too high"; } catch(err) { message.innerHTML = "Input is " + err; } } </script> </body> </html>

HTML Validation #

HTML баталгаажуулалт #

The code above is just an example.

Дээрх код бол зөвхөн жишээ юм.

Modern browsers will often use a combination of JavaScript and built-in HTML validation, using predefined validation rules defined in HTML attributes:

Орчин үеийн хөтөч нь ихэвчлэн HTML шинж чанаруудаар тодорхойлсон баталгаажуулалтын дүрмийг ашиглан JavaScript болон суулгасан HTML баталгаажуулалтыг хослуулан ашигладаг.

<input id="demo" type="number" min="5" max="10" step="1">

You can read more about forms validation in a later chapter of this tutorial.

Маягтыг баталгаажуулах талаар энэ гарын авлагын дараагийн бүлгээс уншиж болно.


The finally Statement #

Эцэст нь мэдэгдэл #

The finally statement lets you execute code, after try and catch, regardless of the result:

Эцэст нь мэдэгдэл нь үр дүнг үл харгалзан кодыг гүйцэтгэх боломжийг олгоно.

Syntax #

try { Block of code to try } catch(err) { Block of code to handle errors } finally { Block of code to be executed regardless of the try / catch result }

Example Жишээ #

function myFunction() { var message, x; message = document.getElementById("p01"); message.innerHTML = ""; x = document.getElementById("demo").value; try { if(x == "") throw "is empty"; if(isNaN(x)) throw "is not a number"; x = Number(x); if(x > 10) throw "is too high"; if(x < 5) throw "is too low"; } catch(err) { message.innerHTML = "Error: " + err + "."; } finally { document.getElementById("demo").value = ""; } }

The Error Object #

Алдаатай объект #

JavaScript has a built in error object that provides error information when an error occurs.

JavaScript нь алдаа гарахад алдааны мэдээллийг өгдөг алдаатай объекттой байдаг.

The error object provides two useful properties: name and message.

Алдааны объект нь нэр ба мессеж гэсэн хоёр ашигтай шинж чанарыг өгдөг.


Error Object Properties #

Алдаатай объектын шинж чанарууд #

Property Description
name Sets or returns an error name

Алдааны нэрийг тохируулах эсвэл буцаах

message Sets or returns an error message (a string)

Алдааны мэдэгдэл (мөр) тохируулах эсвэл буцаах


Error Name Values #

Алдаатай нэрийн утга #

Six different values can be returned by the error name property:

Зургаан өөр утгыг алдаатай нэрийн шинж чанараар буцааж өгч болно:

Error Name Description
EvalError An error has occurred in the eval() function

Eval () функцэд алдаа гарлаа

RangeError A number “out of range” has occurred

“Хүрээнээс гадуур” дугаар гарсан байна

ReferenceError An illegal reference has occurred

Хууль бус лавлагаа гарсан байна

SyntaxError A syntax error has occurred

Синтаксийн алдаа гарлаа

TypeError A type error has occurred

Төрлийн алдаа гарлаа

URIError An error in encodeURI() has occurred

EncodeURI () -д алдаа гарлаа

The six different values are described below.

Зургаан өөр утгыг дор тайлбарлав.


Eval Error #

Алдаа алдаа #

An EvalError indicates an error in the eval() function.

EvalError нь eval () функц дахь алдааг илэрхийлнэ.

Newer versions of JavaScript do not throw EvalError. Use SyntaxError instead.

JavaScript-ийн шинэ хувилбарууд EvalError хаядаггүй. Үүний оронд SyntaxError ашиглана уу.


Range Error #

RangeError is thrown if you use a number that is outside the range of legal values.

Хэрэв та хууль эрх зүйн хэмжигдэхүүнээс хэтэрсэн тоог ашиглавал RangeError хаягдах болно.

For example: You cannot set the number of significant digits of a number to 500.

Жишээлбэл: Та тооны чухал цифрүүдийн тоог 500 болгож тохируулах боломжгүй.

Example Жишээ #

var num = 1; try { num.toPrecision(500); // A number cannot have 500 significant digits } catch(err) { document.getElementById("demo").innerHTML = err.name; }

Reference Error #

Лавлагааны алдаа #

ReferenceError is thrown if you use (reference) a variable that has not been declared:

Хэрэв та зарлаагүй хувьсагчийг (лавлагаа) ашиглавал ReferenceError шидэгдэнэ.

Example Жишээ #

var x; try { x = y + 1; // y cannot be referenced (used) } catch(err) { document.getElementById("demo").innerHTML = err.name; }

Syntax Error #

Синтакс алдаа #

SyntaxError is thrown if you try to evaluate code with a syntax error.

Хэрэв та синтаксийн алдаатай кодыг үнэлэхийг оролдвол SyntaxError хаядаг.

Example Жишээ #

try { eval("alert('Hello)"); // Missing ' will produce an error } catch(err) { document.getElementById("demo").innerHTML = err.name; }

Type Error #

Алдааны төрөл #

TypeError is thrown if you use a value that is outside the range of expected types:

Хэрэв та хүлээгдэж буй төрлүүдийн хүрээнээс гадуур утгыг ашиглавал TypeError хаягдах болно.

Example Жишээ #

var num = 1; try { num.toUpperCase(); // You cannot convert a number to upper case } catch(err) { document.getElementById("demo").innerHTML = err.name; }

URI (Uniform Resource Identifier) Error #

URIError is thrown if you use illegal characters in a URI function:

Хэрэв та URI функцэд хууль бус тэмдэгт ашиглавал URIError хаягдах болно:

Example Жишээ #

try { decodeURI("%%%"); // You cannot URI decode percent signs } catch(err) { document.getElementById("demo").innerHTML = err.name; }

Non-Standard Error Object Properties #

Стандарт бус алдааны объектын шинж чанарууд #

Mozilla and Microsoft defines some non-standard error object properties:

Mozilla болон Microsoft нь зарим стандарт бус алдааны объектын шинж чанаруудыг тодорхойлдог.

fileName (Mozilla)
lineNumber (Mozilla)
columnNumber (Mozilla)
stack (Mozilla)
description (Microsoft)
number (Microsoft)

Do not use these properties in public web sites. They will not work in all browsers.

Эдгээр шинж чанаруудыг нийтийн вэбсайтад бүү ашигла. Тэд бүх хөтөч дээр ажиллахгүй болно.


Complete Error Reference #

Бүрэн алдааны лавлагаа #

For a complete reference of the Error object, go to our Complete JavaScript Error Reference.

Error объектын бүрэн лавлагаа авахын тулд манай Complete JavaScript Error Reference руу орно уу.

Powered by BetterDocs

Leave a Reply