Какое выражение позволяет проверять участки кода на наличие ошибок

С помощью JavaScript выражения try..catch Вы можете проверять участки кода на наличие ошибок.

С помощью JavaScript выражения try..catch Вы можете проверять участки кода на наличие ошибок.

Выражение try..catch

Выражение try..catch позволяет проверять участки кода на наличие ошибок.

Блок try содержит код, который проверяется на ошибки.

Блок catch содержит код, который будет выполнен если в блоке try будет найдена ошибка.

Синтаксис:

try  {
   //Код, который проверяется на наличие ошибок
}
catch(ошибка) {
   //Код, который будет выполнен если в блоке try были найдены ошибки
}

ошибка содержит пояснение к ошибке найденной в блоке try (если ошибка не была найдена переменная останется пустой).

Пример

//Проверим участок кода на ошибки
try 
{ 
//В данном коде ошибка (dddocument вместо document)
dddocument.write('Привет всем!');
}
catch (er)
{
//Выведем пояснение к ошибке
document.write(er);
}

Быстрый просмотр

Блок finally

Данный блок является необязательной частью конструкции try..catch.

Код находящийся в данном блоке начинает выполняться после исполнения кода в блоках try и catch, но перед исполнением команд, которые следуют за данной конструкцией.

Обратите внимание: код в данном блоке будет выполнен независимо от того были ли найдена ошибка в блоке try или нет.

Пример

try 
{ 
document.write('Привет всем!');
}
finally 
{
document.write('<hr />Проверка ошибок была завершена успешно');
}

Быстрый просмотр

Команда throw

Если автоматически сгенерированное пояснение к ошибке Вас не устраивает можете использовать команду throw, чтобы создавать собственные пояснения к возможным ошибкам.

Синтаксис:

Пример

f=prompt('Введите число от 1 до 5: ','');
try  {
   if (f>5) {
      throw 'Число которые Вы ввели больше 5';
   }
   if (f<1) {
      throw 'Число которое Вы ввели меньше 1';
   }
   if (isNaN(f)) {
      throw 'То, что Вы ввели не является числом';
   }
   else {
      document.write('Вы ввели: ' + f);
   }
   }
   catch (er) {
      document.write(er);
   }

Сделайте сами

Задание 1. Найдите с помощью try..catch ошибки в коде ниже и исправьте их.

Задание 1

docuemnt.write('Первое сообщение');
document.wirte('Второе сообщение');
getElementById('mes').innerHTML="Третье сообщение";
getElemeNtById('mes1').innerHTML="Четвертое сообщение";

Try/Catch in JavaScript – How to Handle Errors in JS

Bugs and errors are inevitable in programming. A friend of mine calls them unknown features :).

Call them whatever you want, but I honestly believe that bugs are one of the things that make our work as programmers interesting.

I mean no matter how frustrated you might be trying to debug some code overnight, I am pretty sure you will have a good laugh when you find out that the problem was a simple comma you overlooked, or something like that. Although, an error reported by a client will bring about more of a frown than a smile.

That said, errors can be annoying and a real pain in the behind. That is why in this article, I want to explain something called try / catch in JavaScript.

What is a try/catch block in JavaScript?

A try / catch block is basically used to handle errors in JavaScript. You use this when you don’t want an error in your script to break your code.

While this might look like something you can easily do with an if statement, try/catch gives you a lot of benefits beyond what an if/else statement can do, some of which you will see below.

try{
//...
}catch(e){
//...
}

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

A catch statement lets you handle that error. For example:

try{ 
getData() // getData is not defined 
}catch(e){
alert(e)
}

This is basically how a try/catch is constructed. You put your code in the try block, and immediately if there is an error, JavaScript gives the catch statement control and it just does whatever you say. In this case, it alerts you to the error.

All JavaScript errors are actually objects that contain two properties: the name (for example, Error, syntaxError, and so on) and the actual error message. That is why when we alert e, we get something like ReferenceError: getData is not defined.

Like every other object in JavaScript, you can decide to access the values differently, for example e.name(ReferenceError) and e.message(getData is not defined).

But honestly this is not really different from what JavaScript will do. Although JavaScript will respect you enough to log the error in the console and not show the alert for the whole world to see :).

What, then, is the benefit of try/catch statements?

How to use try/catch statements

The throw Statement

One of the benefits of try/catch is its ability to display your own custom-created error. This is called (throw error).

In situations where you don’t want this ugly thing that JavaScript displays, you can throw your error (an exception) with the use of the throw statement. This error can be a string, boolean, or object. And if there is an error, the catch statement will display the error you throw.

let num =prompt("insert a number greater than 30 but less than 40")
try { 
if(isNaN(num)) throw "Not a number (☉。☉)!" 
else if (num>40) throw "Did you even read the instructions ಠ︵ಠ, less than 40"
else if (num <= 30) throw "Greater than 30 (ب_ب)" 
}catch(e){
alert(e) 
}

This is nice, right? But we can take it a step further by actually throwing an error with the JavaScript constructor errors.

Basically JavaScript categorizes errors into six groups:

  • EvalError — An error occurred in the eval function.
  • RangeError — A number out of range has occurred, for example 1.toPrecision(500). toPrecision basically gives numbers a decimal value, for example 1.000, and a number cannot have 500 of that.
  • ReferenceError —  Using a variable that has not been declared
  • syntaxError — When evaluating a code with a syntax error
  • TypeError — If you use a value that is outside the range of expected types: for example 1.toUpperCase()
  • URI (Uniform Resource Identifier) Error — A URIError is thrown if you use illegal characters in a URI function.

So with all this, we could easily throw an error like throw new Error("Hi there"). In this case the name of the error will be Error and the message Hi there. You could even go ahead and create your own custom error constructor, for example:

function CustomError(message){ 
this.value ="customError";
this.message=message;
}

And you can easily use this anywhere with throw new CustomError("data is not defined").

So far we have learnt about try/catch and how it prevents our script from dying, but that actually depends. Let’s consider this example:

try{ 
console.log({{}}) 
}catch(e){ 
alert(e.message) 
} 
console.log("This should run after the logged details")

But when you try it out, even with the try statement, it still does not work. This is because there are two main types of errors in JavaScript (what I described above –syntaxError and so on – are not really types of errors. You can call them examples of errors): parse-time errors and runtime errors or exceptions.

Parse-time errors are errors that occur inside the code, basically because the engine does not understand the code.

For example, from above, JavaScript does not understand what you mean by {{}}, and because of that, your try / catch has no use here (it won’t work).

On the other hand, runtime errors are errors that occur in valid code, and these are the errors that try/catch will surely find.  

try{ 
y=x+7 
} catch(e){ 
alert("x is not defined")
} 
alert("No need to worry, try catch will handle this to prevent your code from breaking")

Believe it or not, the above is valid code and the try /catch will handle the error appropriately.

The Finally statement

The finally statement acts like neutral ground, the base point or the final ground for your try/ catch block. With finally, you are basically saying no matter what happens in the try/catch (error or no error), this code in the finally statement should run. For example:

let data=prompt("name")
try{ 
if(data==="") throw new Error("data is empty") 
else alert(`Hi ${data} how do you do today`) 
} catch(e){ 
alert(e) 
} finally { 
alert("welcome to the try catch article")
}

Nesting try blocks

You can also nest try blocks, but like every other nesting in JavaScript (for example if, for, and so on), it tends to get clumsy and unreadable, so I advise against it. But that is just me.

Nesting try blocks gives you the advantage of using just one catch statement for multiple try statements. Although you could also decide to write a catch statement for each try block, like this:

try { 
try { 
throw new Error('oops');
} catch(e){
console.log(e) 
} finally { 
console.log('finally'); 
} 
} catch (ex) { 
console.log('outer '+ex); 
}

In this case, there won’t be any error from the outer try block because nothing is wrong with it. The error comes from the inner try block, and it is already taking care of itself (it has it own catch statement). Consider this below:

try { 
try { 
throw new Error('inner catch error'); 
} finally {
console.log('finally'); 
} 
} catch (ex) { 
console.log(ex);
}

This code above works a little bit differently: the error occurs in the inner try block with no catch statement but instead with a finally statement.

Note that try/catch can be written in three different ways: try...catch, try...finally, try...catch...finally), but the error is throw from this inner try.

The finally statement for this inner try will definitely work, because like we said earlier, it works no matter what happens in try/catch. But even though the outer try does not have an error, control is still given to its catch to log an error. And even better, it uses the error we created in the inner try statement because the error is coming from there.

If we were to create an error for the outer try, it would still display the inner error created, except the inner one catches its own error.

You can play around with the code below by commenting out the inner catch.

try { 
try { 
throw new Error('inner catch error');
} catch(e){ //comment this catch out
console.log(e) 
} finally { 
console.log('finally'); 
} 
throw new Error("outer catch error") 
} catch (ex) { 
console.log(ex);
}

The Rethrow Error

The catch statement actually catches all errors that come its way, and sometimes we might not want that. For example,

"use strict" 
let x=parseInt(prompt("input a number less than 5")) 
try{ 
y=x-10 
if(y>=5) throw new Error(" y is not less than 5") 
else alert(y) 
}catch(e){ 
alert(e) 
}

Let’s assume for a second that the number inputted will be less than 5 (the purpose of «use strict» is to indicate that the code should be executed in «strict mode»). With strict mode, you can not, for example, use undeclared variables (source).

I want the try statement to throw an error of y is not… when the value of y is greater than 5 which is close to impossible. The error above should be for y is not less… and not y is undefined.

In situations like this, you can check for the name of the error, and if it is not what you want, rethrow it:

"use strict" 
let x = parseInt(prompt("input a number less than 5"))
try{
y=x-10 
if(y>=5) throw new Error(" y is not less than 5") 
else alert(y) 
}catch(e){ 
if(e instanceof ReferenceError){ 
throw e
}else alert(e) 
} 

This will simply rethrow the error for another try statement to catch or break the script here. This is useful when you want to only monitor a particular type of error and other errors that might occur as a result of negligence should break the code.

Conclusion

In this article, I have tried to explain the following concepts relating to try/catch:

  • What try /catch statements are and when they work
  • How to throw custom errors
  • What the finally statement is and how it works
  • How Nesting try / catch statements work
  • How to rethrow errors

Thank you for reading. Follow me on twitter @fakoredeDami.



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Try/Catch in JavaScript – How to Handle Errors in JS

Bugs and errors are inevitable in programming. A friend of mine calls them unknown features :).

Call them whatever you want, but I honestly believe that bugs are one of the things that make our work as programmers interesting.

I mean no matter how frustrated you might be trying to debug some code overnight, I am pretty sure you will have a good laugh when you find out that the problem was a simple comma you overlooked, or something like that. Although, an error reported by a client will bring about more of a frown than a smile.

That said, errors can be annoying and a real pain in the behind. That is why in this article, I want to explain something called try / catch in JavaScript.

What is a try/catch block in JavaScript?

A try / catch block is basically used to handle errors in JavaScript. You use this when you don’t want an error in your script to break your code.

While this might look like something you can easily do with an if statement, try/catch gives you a lot of benefits beyond what an if/else statement can do, some of which you will see below.

try{
//...
}catch(e){
//...
}

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

A catch statement lets you handle that error. For example:

try{ 
getData() // getData is not defined 
}catch(e){
alert(e)
}

This is basically how a try/catch is constructed. You put your code in the try block, and immediately if there is an error, JavaScript gives the catch statement control and it just does whatever you say. In this case, it alerts you to the error.

All JavaScript errors are actually objects that contain two properties: the name (for example, Error, syntaxError, and so on) and the actual error message. That is why when we alert e, we get something like ReferenceError: getData is not defined.

Like every other object in JavaScript, you can decide to access the values differently, for example e.name(ReferenceError) and e.message(getData is not defined).

But honestly this is not really different from what JavaScript will do. Although JavaScript will respect you enough to log the error in the console and not show the alert for the whole world to see :).

What, then, is the benefit of try/catch statements?

How to use try/catch statements

The throw Statement

One of the benefits of try/catch is its ability to display your own custom-created error. This is called (throw error).

In situations where you don’t want this ugly thing that JavaScript displays, you can throw your error (an exception) with the use of the throw statement. This error can be a string, boolean, or object. And if there is an error, the catch statement will display the error you throw.

let num =prompt("insert a number greater than 30 but less than 40")
try { 
if(isNaN(num)) throw "Not a number (☉。☉)!" 
else if (num>40) throw "Did you even read the instructions ಠ︵ಠ, less than 40"
else if (num <= 30) throw "Greater than 30 (ب_ب)" 
}catch(e){
alert(e) 
}

This is nice, right? But we can take it a step further by actually throwing an error with the JavaScript constructor errors.

Basically JavaScript categorizes errors into six groups:

  • EvalError — An error occurred in the eval function.
  • RangeError — A number out of range has occurred, for example 1.toPrecision(500). toPrecision basically gives numbers a decimal value, for example 1.000, and a number cannot have 500 of that.
  • ReferenceError —  Using a variable that has not been declared
  • syntaxError — When evaluating a code with a syntax error
  • TypeError — If you use a value that is outside the range of expected types: for example 1.toUpperCase()
  • URI (Uniform Resource Identifier) Error — A URIError is thrown if you use illegal characters in a URI function.

So with all this, we could easily throw an error like throw new Error("Hi there"). In this case the name of the error will be Error and the message Hi there. You could even go ahead and create your own custom error constructor, for example:

function CustomError(message){ 
this.value ="customError";
this.message=message;
}

And you can easily use this anywhere with throw new CustomError("data is not defined").

So far we have learnt about try/catch and how it prevents our script from dying, but that actually depends. Let’s consider this example:

try{ 
console.log({{}}) 
}catch(e){ 
alert(e.message) 
} 
console.log("This should run after the logged details")

But when you try it out, even with the try statement, it still does not work. This is because there are two main types of errors in JavaScript (what I described above –syntaxError and so on – are not really types of errors. You can call them examples of errors): parse-time errors and runtime errors or exceptions.

Parse-time errors are errors that occur inside the code, basically because the engine does not understand the code.

For example, from above, JavaScript does not understand what you mean by {{}}, and because of that, your try / catch has no use here (it won’t work).

On the other hand, runtime errors are errors that occur in valid code, and these are the errors that try/catch will surely find.  

try{ 
y=x+7 
} catch(e){ 
alert("x is not defined")
} 
alert("No need to worry, try catch will handle this to prevent your code from breaking")

Believe it or not, the above is valid code and the try /catch will handle the error appropriately.

The Finally statement

The finally statement acts like neutral ground, the base point or the final ground for your try/ catch block. With finally, you are basically saying no matter what happens in the try/catch (error or no error), this code in the finally statement should run. For example:

let data=prompt("name")
try{ 
if(data==="") throw new Error("data is empty") 
else alert(`Hi ${data} how do you do today`) 
} catch(e){ 
alert(e) 
} finally { 
alert("welcome to the try catch article")
}

Nesting try blocks

You can also nest try blocks, but like every other nesting in JavaScript (for example if, for, and so on), it tends to get clumsy and unreadable, so I advise against it. But that is just me.

Nesting try blocks gives you the advantage of using just one catch statement for multiple try statements. Although you could also decide to write a catch statement for each try block, like this:

try { 
try { 
throw new Error('oops');
} catch(e){
console.log(e) 
} finally { 
console.log('finally'); 
} 
} catch (ex) { 
console.log('outer '+ex); 
}

In this case, there won’t be any error from the outer try block because nothing is wrong with it. The error comes from the inner try block, and it is already taking care of itself (it has it own catch statement). Consider this below:

try { 
try { 
throw new Error('inner catch error'); 
} finally {
console.log('finally'); 
} 
} catch (ex) { 
console.log(ex);
}

This code above works a little bit differently: the error occurs in the inner try block with no catch statement but instead with a finally statement.

Note that try/catch can be written in three different ways: try...catch, try...finally, try...catch...finally), but the error is throw from this inner try.

The finally statement for this inner try will definitely work, because like we said earlier, it works no matter what happens in try/catch. But even though the outer try does not have an error, control is still given to its catch to log an error. And even better, it uses the error we created in the inner try statement because the error is coming from there.

If we were to create an error for the outer try, it would still display the inner error created, except the inner one catches its own error.

You can play around with the code below by commenting out the inner catch.

try { 
try { 
throw new Error('inner catch error');
} catch(e){ //comment this catch out
console.log(e) 
} finally { 
console.log('finally'); 
} 
throw new Error("outer catch error") 
} catch (ex) { 
console.log(ex);
}

The Rethrow Error

The catch statement actually catches all errors that come its way, and sometimes we might not want that. For example,

"use strict" 
let x=parseInt(prompt("input a number less than 5")) 
try{ 
y=x-10 
if(y>=5) throw new Error(" y is not less than 5") 
else alert(y) 
}catch(e){ 
alert(e) 
}

Let’s assume for a second that the number inputted will be less than 5 (the purpose of «use strict» is to indicate that the code should be executed in «strict mode»). With strict mode, you can not, for example, use undeclared variables (source).

I want the try statement to throw an error of y is not… when the value of y is greater than 5 which is close to impossible. The error above should be for y is not less… and not y is undefined.

In situations like this, you can check for the name of the error, and if it is not what you want, rethrow it:

"use strict" 
let x = parseInt(prompt("input a number less than 5"))
try{
y=x-10 
if(y>=5) throw new Error(" y is not less than 5") 
else alert(y) 
}catch(e){ 
if(e instanceof ReferenceError){ 
throw e
}else alert(e) 
} 

This will simply rethrow the error for another try statement to catch or break the script here. This is useful when you want to only monitor a particular type of error and other errors that might occur as a result of negligence should break the code.

Conclusion

In this article, I have tried to explain the following concepts relating to try/catch:

  • What try /catch statements are and when they work
  • How to throw custom errors
  • What the finally statement is and how it works
  • How Nesting try / catch statements work
  • How to rethrow errors

Thank you for reading. Follow me on twitter @fakoredeDami.



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Конструкция try...catch пытается выполнить инструкции в блоке try, и, в случае ошибки, выполняет блок catch.

Синтаксис

try {
   try_statements
}
[catch (exception_var_1 if condition_1) { // не стандартно
   catch_statements_1
}]
...
[catch (exception_var_2) {
   catch_statements_2
}]
[finally {
   finally_statements
}]
try_statements

Инструкции для выполнения.

catch_statements_1, catch_statements_2

Инструкции, которые будут выполнены, если произойдёт ошибка в блоке try.

exception_var_1, exception_var_2

Идентификатор для хранения объекта ошибки, который впоследствии используется в блоке catch

condition_1

Условное выражение.

finally_statements

Инструкции, которые выполняются после завершения блока try. Выполнение происходит в независимости от того, произошла ошибка или нет.

Описание

Конструкция try содержит блок try, в котором находится одна или несколько инструкций (Блок ({} ) обязательно должен присутствовать, даже если выполняется всего одна инструкция), и хотя бы один блок catch или finally. Таким образом, есть три основные формы конструкции try:

  1. try {...} catch {...}
  2. try {...} finally {...}
  3. try {...} catch {...} finally {...}

Блок catch содержит инструкции, которые будут выполнены, если в блоке try произошла ошибка. Если любая инструкция в блоке try выбрасывает исключение, то управление сразу же переходит в блок catch. Если в блок try не было выброшено исключение, то блок catch не выполняется.

Блок finally выполнится после выполнения блоков try и catch, но перед инструкциями, следующими за конструкцией try...catch. Он выполняется всегда, в независимости от того, было исключение или нет.

Вы можете использовать вложенные конструкции try. Если внутренняя конструкция try не имеет блока catch (такое может быть при её использовании в виде try {...} finaly {...}, потому что try {...} не может быть без блоков catch или finally), будет вызван сatch внешней конструкции try.

Конструкция try также используется для обработки исключений JavaScript (то есть, выброшенных внутренними функциями языка или парсером). Загляните в JavaScript руководство для дополнительной информации о JavaScript исключениях.

Безусловный блок catch

При использовании блока catch, он вызывается для любого исключения в блоке try. Например, когда в следующем коде происходит ошибка, управление переходит к блоку catch.

try {
   throw 'myException'; // создание исключения
}
catch (e) {
   // инструкции для обработки ошибок
   logMyErrors(e); // передать объект исключения обработчику ошибок
}

Блок catch задаёт идентификатор (e в примере выше) который содержит объект исключения (в примере выше — значение, переданное оператору throw). Область видимости этого объекта ограничивается блоком catch.

Условный блок catch

«Условные блоки catch» можно создавать, используя try...catch с if...else if...else, как здесь:

try {
  myroutine(); // может выбрасывать три вида исключений
} catch (e) {
  if (e instanceof TypeError) {
    // обработка исключения TypeError
  } else if (e instanceof RangeError) {
    // обработка исключения RangeError
  } else if (e instanceof EvalError) {
    // обработка исключения EvalError
  } else {
    // обработка остальных исключений
    logMyErrors(e); // передать обработчику ошибок
  }
}

Частый сценарий использования — обработать известные исключения, а при неизвестных ошибках, пробросить их дальше:

try {
  myRoutine();
} catch(e) {
  if (e instanceof RangeError) {
    // обработка известного исключения, с которым
    // понятно, что делать
  } else {
    throw e; // пробросить неизвестные ошибки
  }
}

Примечание: Обратите внимание: Firefox раньше поддерживал краткую запись условных блоков catch:

try {
  myroutine(); // может выбрасывать три вида исключения
} catch (e if e instanceof TypeError) {
  // обработка исключений TypeError
} catch (e if e instanceof RangeError) {
  // обработка исключений RangeError
} catch (e if e instanceof EvalError) {
  // обработка исключений EvalError
} catch (e) {
  // обработка остальных исключения
  logMyErrors(e);
}

Однако, такой синтаксис никогда не был частью спецификации ECMAScript и был удалён из Firefox после версии 59. Сейчас он не поддерживается ни в одном браузере.

Идентификатор исключения

Когда в блоке try выбрасывается исключение, exception_var (т. е. e в конструкции catch (e)) содержит значение исключения. Его можно использовать, чтобы получить больше информации об выброшенном исключении. Идентификатор доступен только в области видимости блока catch.

try {
  if (!firstValidation()) {
    throw 1;
  }
  if (!secondValidation()) {
    throw 2;
  }
} catch (e) {
  // Выводит 1 или 2 (если не произошло никаких других ошибок)
  console.log(e);
}

Блок finally

Блок finally содержит код который будет запущен после кода в блоках try и catch. Обратите внимание, что код в блоке finally запускается в независимости от того, было ли выброшено исключение или нет. Также код в блоке finally будет запущен вне зависимости от того, присутствует блок catch или нет. Блок finally можно использовать для того, чтобы скрипт безопасно завершил работу в случае ошибки. Например, если необходимо освободить память и ресурсы которые использовал скрипт.

Наличие специального блока, связанного с ошибкой, который выполняется вне зависимости от наличия исключительной ситуации, может показаться странным, но эта конструкция на самом деле весьма полезна. Рассмотрим пример кода:

function expensiveCalculations() {
  // Сложные вычисления
}

function maybeThrowError() {
  // Функция, которая может выбросить исключение
  if(Math.random() > 0.5) throw new Error()
}

try {
  // Теперь при прокрутке страницы будут происходить
  // сложные вычисления, что сильно скажется на
  // производительности
  window.addEventListener('scroll', expensiveCalculations)
  maybeThrowError()
} catch {
  // Если функция maybeThrowError выбросит исключения,
  // управление сразу перейдёт в блок catch и
  // сложные вычисления продолжат выполняться до
  // перезагрузки страницы
  maybeThrowError()
}
window.removeEventListener('scroll', expensiveCalculations)

В этом примере, если функция maybeThrowError выбросит исключение внутри блока try, управление перейдёт в блок catch. Если и в блоке catch эта функция тоже выбросит исключение, то выполнение кода прервётся, и обработчик события не будет снят, пока пользователь не перезагрузит страницу, что плохо скажется на скорости работы. Для того, чтобы избежать таких ситуаций, следует использовать блок finally:

try {
  window.addEventListener('scroll', expensiveCalculations)
  maybeThrowError()
} catch {
  maybeThrowError()
} finally {
  window.removeEventListener('scroll', expensiveCalculations)
}

Другой пример: работа с файлами. В следующем фрагменте кода показывается, как скрипт открывает файл и записывает в него какие-то данные (в серверном окружении JavaScript имеет доступ к файловой системе). Во время записи может произойти ошибка. Но после открытия файл очень важно закрыть, потому что незакрытый файл может привести к утечкам памяти. В таких случаях используется блок finally:

openMyFile();
try {
   // Сделать что-то с файлом
   writeMyFile(theData);
}
finally {
   closeMyFile(); // Закрыть файл, что бы ни произошло
}

Примеры

Вложенные блоки try

Для начала давайте посмотрим что делает этот код:

try {
  try {
    throw new Error('упс');
  }
  finally {
    console.log('finally');
  }
}
catch (e) {
  console.error('внешний блок catch', e.message);
}

// Вывод:
// "finally"
// "внешний блок catch" "упс"

Теперь отловим исключение во внутреннем блоке try, добавив к нему блок catch:

try {
  try {
    throw new Error('упс');
  }
  catch (e) {
    console.error('внутренний блок catch', e.message);
  }
  finally {
    console.log('finally');
  }
}
catch (e) {
  console.error('внешний блок catch', e.message);
}

// Output:
// "внутренний блок catch" "упс"
// "finally"

Наконец, пробросим ошибку

try {
  try {
    throw new Error('упс');
  }
  catch (e) {
    console.error('внутренний блок catch', e.message);
    throw e;
  }
  finally {
    console.log('finally');
  }
}
catch (e) {
  console.error('внешний блок catch', e.message);
}

// Вывод:
// "внутренний блок catch" "oops"
// "finally"
// "внешний блок catch" "oops"

Любое исключение будет передано только в ближайший блок catch, если он не пробросит его дальше. Все исключения, выброшенными внутренними блоками (потому что код в блоке catch также может выбросить исключение), будут пойманы внешними.

Возвращение значения из блока finally

Если блок finally возвращает какое-либо значение, оно становится значением, которое возвращает вся конструкция try...catch...finally, вне зависимости от любых инструкций return в блоках try и catch. Также игнорируются исключения, выброшенные блоком catch.

try {
  try {
    throw new Error('упс');
  }
  catch (e) {
    console.error('внутренний блок catch', e.message);
    throw e;
  }
  finally {
    console.log('finally');
    return;
  }
}
catch (e) {
  console.error('внешний блок catch', e.message);
}

// Output:
// "внутренний блок catch" "упс"
// "finally"

«упс» не доходит до внешнего блока из-за инструкции return в блоке finally. То же самое произойдёт с любым значением, возвращаемым из блока catch.

Спецификации

Specification
ECMAScript Language Specification
# sec-try-statement

Совместимость

BCD tables only load in the browser

Смотрите также



Оператор try позволяет вам проверить блок кода на наличие ошибок.

Оператор catch позволяет вам обработать ошибку.

Оператор throw позволяет создавать собственные ошибки.

Оператор finally позволяет выполнить код, после того, как попытаться поймать, независимо от результата.


Ошибки будут!

При выполнении кода JavaScript могут возникать разные ошибки.

Ошибки могут быть ошибками кодирования, допущенны программистом, ошибками из-за неправильного ввода или другими непредвиденными ситуациями.

Пример

В этом примере мы в место alert написали adddlert, чтобы намеренно выдать ошибку:

<p id=»demo»></p>

<script>
try {
  adddlert(«Добро пожаловать!»);
}
catch(err) {
 
document.getElementById(«demo»).innerHTML = err.message;
}
</script>

Попробуйте сами »

JavaScript перехватывает adddlert, как ошибку и выполняет код перехвата для ее обработки.


JavaScript try и catch

Оператор try, позволяет обнаружить блок кода, который будет проверяться на наличие ошибок во время его выполнения.

Оператор catch, позволяет поймать блок кода, который будет выполняться, если в блоке try возникает ошибка.

Оператор JavaScript try и catch идут в парах:

try {
  Блок кода для проверки
}
catch(err) {
  Блок кода для обработки ошибок
}



JavaScript выдает ошибки

Когда происходит ошибка, JavaScript обычно останавливается и генерирует сообщение об ошибке.

Технический термин для этого: JavaScript вызовет исключение (выдаст ошибку).

JavaScript фактически создаст объект Error с двумя свойствами: name и message.


Оператор throw

Оператор throw позволяет создать пользовательскую ошибку.

Технически вы можете сгенерировать исключение (сгенерировать ошибку).

Исключением может быть JavaScript String, Number, Boolean или Object:

throw «Слишком большой»;    // пропустить текст
throw 500;          // пропустить число

Если вы используете throw вместе с try и catch, вы можете контролировать выполнение программы и генерировать собственные сообщения об ошибках.


Пример проверки ввода

В этом примере исследуется ввод. Если значение неверно, генерируется исключение (ошибка).

Исключение (err) перехватывается оператором catch, и отображается настраиваемое сообщение об ошибке:

<!DOCTYPE html>
<html>
<body>

<p>Пожалуйста, введите число от 5 до 10:</p>

<input id=»demo» type=»text»>
<button type=»button»
onclick=»myFunction()»>Ввод текста</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 «пусто»;
   
if(isNaN(x)) throw «не число»;
   
x = Number(x);
    if(x < 5) throw
«слишком маленькое»;
    if(x > 10) throw «слишком
большое»;
  }
  catch(err) {
    message.innerHTML =
«Вывод » + err;
  }
}
</script>

</body>
</html>

Попробуйте сами »


Проверка HTML на валидность

Код выше — является просто примером.

Современные браузеры часто используют комбинацию JavaScript и встроенной проверки HTML, используя предопределенные правила проверки, определенные в атрибутах HTML:

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

Вы можете узнать больше о проверке форм в следующей главе этого руководства.


Оператор finally

Оператор finally позволяет выполнить код, после try и catch, еще раз попытаться поймать, независимо от результата:

Синтаксис

try {
  блок кода для попытки обнаружить ошибки
}
catch(err) {
  блок кода для обработки поймать ошибки
}

finally {
  блок кода, который будет выполняться независимо от результата try/catch
}

Пример

function myFunction() {
  var message, x;
  message =
document.getElementById(«p01»);
  message.innerHTML = «»;
  x =
document.getElementById(«demo»).value;
 
try {
   
if(x == «») throw «пусто»;
    if(isNaN(x))
throw «не число»;
   
x = Number(x);
    if(x >
10) throw «слишком большое»;
    if(x <
5) throw «слишком маленькое»;
  }
  catch(err)
{
    message.innerHTML = «Ошибка: » +
err + «.»;
  }
  finally {
    document.getElementById(«demo»).value = «»;
  }
}

Попробуйте сами »


Объект Error

JavaScript имеет встроенный объект Error, который предоставляет информацию об ошибке при возникновении ошибки.

Объект Error предоставляет два полезных свойства: имя и сообщение.


Свойства объекта Error

Свойство Описание
имя Задает или возвращает имя ошибки
сообщение Устанавливает или возвращает сообщение об ошибке (строку)

Значения Error Name

Шесть различных значений могут быть возвращены свойством Error Name:

Error Name Описание
EvalError Произошла ошибка в функции eval()
RangeError Произошло число «вне допустимого диапазона»
ReferenceError Произошла недопустимая ссылка
SyntaxError Произошла синтаксическая ошибка
TypeError Произошла ошибка типа
URIError Произошла ошибка в encodeURI()

Ниже описаны шесть различных значений.


Ошибка EvalError

Один EvalError указывает на ошибку в функции eval().

Новые версии JavaScript не генерируют EvalError. Вместо этого используйте SyntaxError.


Ошибка RangeError

Ошибка RangeError генерируется, если вы используете число, выходящее за пределы диапазона допустимых значений.

Например: Вы не можете установить количество значащих цифр числа на 500.

Пример

var num = 1;
try {
  num.toPrecision(500);   // Число не может содержать 500 значащих цифр
}
catch(err) {
  document.getElementById(«demo»).innerHTML = err.name;
}

Попробуйте сами »


Ошибка ReferenceError

Ошибка ReferenceError генерируется, если вы используете (ссылаетесь на неё) переменную,
которая не была объявлена:

Пример

var x;
try {
  x = y + 1;   // на y нельзя ссылаться (использовать)
}
catch(err) {
  document.getElementById(«demo»).innerHTML = err.name;
}

Попробуйте сами »


Ошибка SyntaxError

Ошибка SyntaxError генерируется, если вы пытаетесь запустить код с синтаксической ошибкой.

Пример

try {
  eval(«alert(‘Привет)»);   // Отсутствует ‘вызовет ошибку
}
catch(err) {
  document.getElementById(«demo»).innerHTML = err.name;
}

Попробуйте сами »


Ошибка TypeError

Ошибка TypeError генерируется, если вы используете значение, которое находится за пределами диапазона ожидаемых типов:

Пример

var num = 1;
try {
  num.toUpperCase();   // Вы не можете преобразовать число в верхний регистр
}
catch(err) {
  document.getElementById(«demo»).innerHTML = err.name;
}

Попробуйте сами »


Ошибка URIError (Единый идентификатор ресурса)

Ошибка URIError генерируется, если вы используете недопустимые символы в функции URI:

Пример

try {
  decodeURI(«%%%»);   // Вы не можете декодировать знаки процента URI
}
catch(err) {
  document.getElementById(«demo»).innerHTML = err.name;
}

Попробуйте сами »


Нестандартные свойства объекта ошибок

Mozilla и Microsoft определяют некоторые нестандартные свойства объекта ошибки:

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

Не используйте эти свойства на общедоступных веб-сайтах. Они не будут работать во всех браузерах.


Полный справочник ошибок

Чтобы получить полную информацию об объекте Error, перейдите в Полный справочник ошибок JavaScript ..


Оператор try позволяет проверить блок кода на возникновение ошибок.

Оператор catch позволяет обрабатывать возникшую ошибку.

Оператор throw позволяет генерировать пользовательские ошибки.

Оператор finally позволяет выполнять код после операторов try и catch не зависимо от результата.

Ошибки будут!

Во время выполнения кода JavaScript, могут возникать разные ошибки.

Это могут быть ошибки кодирования, сделанные программистом, ошибки, возникающие в результате ввода неверных данных, и другие непредвиденные вещи.

В следующем примере, чтобы умышленно создать ошибку, мы вместо команды alert написали adddlert:


<p id="demo"></p>

<script>
try {
    adddlert("Добро пожаловать, гость!");
}
catch(err) {
    document.getElementById("demo").innerHTML = err.message;
}
</script>

JavaScript перехватит adddlert как ошибку и выполнит код в операторе catch, чтобы ее обработать.

Операторы try и catch

Оператор try определяет блок кода, который во время выполнения будет проверяться на возникновение ошибок.

Оператор catch определяет блок кода, который будет выполняться, если в блоке оператора try возникнет ошибка.

Операторы try и catch всегда используются в паре:


try {
     // проверяемый блок кода
}
 catch(err) {
     // блок кода для обработки ошибок
} 

JavaScript генерирует ошибки

Когда возникает ошибка, обычно интерпретатор JavaScript останавливает выполнение кода и генерирует сообщение об ошибке.

Если говорить техническими терминами, то интерпретатор JavaScript сгенерирует исключение (сгенерирует ошибку).

На самом деле интерпретатор JavaScript создаст объект Error с двумя свойствами — name и message.

Оператор throw

Оператор throw позволяет создавать пользовательские ошибки.

В техническом смысле вы можете генерировать исключения (генерировать ошибки).

Исключения могут быть строкой, числом, логическим значением или объектом JavaScript:


throw "Слишком большой";
throw 500;

Используя оператор throw вместе с try и catch, вы можете контролировать ход программы и генерировать пользовательские сообщения об ошибках.

Пример проверки ввода

В следующем примере проверяются данные ввода. Если введено неверное значение, то генерируется исключение (err).

Исключение (err) перехватывается оператором catch, и выводится пользовательское сообщение об ошибке:


<!DOCTYPE html>
<html>
<body>

<p>Введите число от 5 до 10:</p>

<input id="demo" type="text">
<button type="button" onclick="myFunction()">Проверка ввода</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 "пусто";
        if(isNaN(x)) throw "не число";
        x = Number(x);
        if(x < 5) throw "слишком мало";
        if(x > 10) throw "слишком много";
    }
    catch(err) {
        message.innerHTML = "Вы ввели " + err;
    }
}
</script>

</body>
</html>

HTML проверка

Приведенный выше код это всего лишь пример.

Современные браузеры часто используют комбинацию JavaScript и встроенной HTML проверки, реализуемой при помощи предопределенных правил, заданных в HTML атрибутах:


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

Оператор finally

Оператор finally позволяет выполнить код после операторов try и catch, независимо от результатов проверки:


try {
     // проверяемый блок кода
}
catch(err) {
     // блок кода для обработки ошибок
} 
finally {
    // блок кода, выполняемый не зависимо от результата операторов try / catch
}

Пример:


function myFunction() {
    var message, x;
    message = document.getElementById("p01");
    message.innerHTML = "";
    x = document.getElementById("demo").value;
    try {
        if(x == "") throw "пусто";
        if(isNaN(x)) throw "не число";
        x = Number(x);
        if(x < 5) throw "слишком мало";
        if(x > 10) throw "слишком много";
    }
    catch(err) {
        message.innerHTML = "Ошибка: " + err + ".";
    }
    finally {
        document.getElementById("demo").value = "";
    }
} 

Объект Error

В JavaScript есть встроенный объект Error, который предоставляет информацию по возникшей ошибке.

Объект Error предоставляет два полезных свойства:

Свойство Описание
name Устанавливает или возвращает имя ошибки
message Устанавливает или возвращает сообщение об ошибке (строку)

Значения свойства name

В свойстве name объекта Error может быть возвращено шесть различных значений:

Имя ошибки Описание
EvalError Ошибка в функции eval()
RangeError Число «за пределами диапазона»
ReferenceError Недопустимая ссылка (обращение)
SyntaxError Синтаксическая ошибка
TypeError Ошибка типов
URIError Ошибка в encodeURI()

EvalError

EvalError указывает на то, что возникла ошибка в функции eval().

В более новых версиях JavaScript никогда не генерируется ошибка EvalError. Вместо нее используется SyntaxError.

RangeError

Ошибка RangeError возникает, если вы используете число, которое выходит за пределы диапазона допустимых значений.

Например, нельзя задать число с 500 знаковыми цифрами.


var num = 1;
try {
    num.toPrecision(500);   // Число не может иметь 500 знаковых цифр
}
catch(err) {
    document.getElementById("demo").innerHTML = err.name;
} 

ReferenceError

Ошибка ReferenceError возникает в том случае, когда вы используете (ссылаетесь) переменную, которая не была декларирована:


var x;
try {
    x = y + 1;   // нельзя использовать (ссылаться на) переменную y
}
catch(err) {
    document.getElementById("demo").innerHTML = err.name;
} 

SyntaxError

Ошибка SyntaxError возникает, когда вы пытаетесь выполнить код с синтаксическими ошибками.


try {
    eval("alert('Hello)");   // Пропуск ' приведет к синтаксической ошибке
}
catch(err) {
     document.getElementById("demo").innerHTML = err.name;
} 

TypeError

Ошибка TypeError возникает, когда вы используете значение, выходящее за пределы диапазона ожидаемых типов:


var num = 1;
try {
    num.toUpperCase();   // Нельзя преобразовать число в верхний регистр
}
catch(err) {
    document.getElementById("demo").innerHTML = err.name;
} 

URIError

Ошибка URIError возникает, когда вы используете недопустимые символы в функциях URI:


try {
    decodeURI("%%%");   // Нельзя декодировать эти символы процентов
}
catch(err) {
    document.getElementById("demo").innerHTML = err.name;
} 

Нестандартные свойства объекта Error

Mozilla и Microsoft определяют ряд нестандартных свойств объекта Error:

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

Никогда не используйте эти свойства в публичном веб-сайте. Они не будут работать во всех браузерах.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Какое утверждение ошибочно у существительного есть только 2 склонения
  • Какое было ошибочное мнение ученых предложивших клеточную теорию
  • Какого типа ошибки многопоточности позволяет обнаружить intel parallel inspector
  • Какого роста error sans
  • Какого правила необходимо придерживаться чтобы избежать ошибок поведения

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии