- TypeError
- Синтаксис
- Параметры
- Описание
- Свойства
- Методы
- Экземпляры объекта TypeError
- Свойства
- Методы
- Примеры
- Пример: перехват исключения TypeError
- Пример: возбуждение исключения TypeError
- Спецификации
- Совместимость с браузерами
- Смотрите также
- Found a content problem with this page?
- throw
- Try it
- Syntax
- Description
- Automatic semicolon insertion
- Examples
- Throwing a user-defined error
- Throwing an existing object
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- TypeError() constructor
- Syntax
- Parameters
- Examples
- Catching a TypeError
- Creating a TypeError
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- TypeError
- Constructor
- Instance properties
- Examples
- Catching a TypeError
- Creating a TypeError
- Specifications
TypeError
Объект TypeError представляет ошибку, возникающую, когда значение имеет не ожидаемый тип.
Синтаксис
new TypeError([message[, fileName[, lineNumber]]])
Параметры
Необязательный параметр. Человеко-читаемое описание ошибки.
Необязательный параметр. Имя файла, содержащего код, вызвавший исключение.
Необязательный параметр. Номер строки кода, вызвавшей исключение.
Описание
Исключение TypeError выбрасывается, когда операнд или аргумент, переданный в функцию, не совместим с типом, ожидаемым оператором или функцией.
Свойства
Позволяет добавлять свойства в объект TypeError .
Методы
Глобальный объект TypeError не содержит собственных методов, однако, он наследует некоторые методы из цепочки прототипов.
Экземпляры объекта TypeError
Свойства
Методы
Примеры
Пример: перехват исключения TypeError
try null.f(); > catch (e) console.log(e instanceof TypeError); // true console.log(e.message); // "null has no properties" - null не имеет свойств console.log(e.name); // "TypeError" console.log(e.fileName); // "Scratchpad/1" console.log(e.lineNumber); // 2 console.log(e.columnNumber); // 2 console.log(e.stack); // "@Scratchpad/2:2:3\n" >
Пример: возбуждение исключения TypeError
try throw new TypeError('Привет', 'someFile.js', 10); > catch (e) console.log(e instanceof TypeError); // true console.log(e.message); // "Привет" console.log(e.name); // "TypeError" console.log(e.fileName); // "someFile.js" console.log(e.lineNumber); // 10 console.log(e.columnNumber); // 0 console.log(e.stack); // "@Scratchpad/2:2:9\n" >
Спецификации
Совместимость с браузерами
BCD tables only load in the browser
Смотрите также
Found a content problem with this page?
This page was last modified on 22 окт. 2022 г. by MDN contributors.
Your blueprint for a better internet.
throw
The throw statement throws a user-defined exception. Execution of the current function will stop (the statements after throw won’t be executed), and control will be passed to the first catch block in the call stack. If no catch block exists among caller functions, the program will terminate.
Try it
Syntax
Description
The throw statement is valid in all contexts where statements can be used. Its execution generates an exception that penetrates through the call stack. For more information on error bubbling and handling, see Control flow and error handling.
The throw keyword can be followed by any kind of expression, for example:
throw error; // Throws a previously defined value (e.g. within a catch block) throw new Error("Required"); // Throws a new Error object
In practice, the exception you throw should always be an Error object or an instance of an Error subclass, such as RangeError . This is because code that catches the error may expect certain properties, such as message , to be present on the caught value. For example, web APIs typically throw DOMException instances, which inherit from Error.prototype .
Automatic semicolon insertion
The syntax forbids line terminators between the throw keyword and the expression to be thrown.
The code above is transformed by automatic semicolon insertion (ASI) into:
This is invalid code, because unlike return , throw must be followed by an expression.
To avoid this problem (to prevent ASI), you could use parentheses:
Examples
Throwing a user-defined error
This example defines a function that throws a TypeError if the input is not of the expected type.
function isNumeric(x) return ["number", "bigint"].includes(typeof x); > function sum(. values) if (!values.every(isNumeric)) throw new TypeError("Can only add numbers"); > return values.reduce((a, b) => a + b); > console.log(sum(1, 2, 3)); // 6 try sum("1", "2"); > catch (e) console.error(e); // TypeError: Can only add numbers >
Throwing an existing object
This example calls a callback-based async function, and throws an error if the callback receives an error.
readFile("foo.txt", (err, data) => if (err) throw err; > console.log(data); >);
Errors thrown this way are not catchable by the caller and will cause the program to crash unless (a) the readFile function itself catches the error, or (b) the program is running in a context that catches top-level errors. You can handle errors more naturally by using the Promise() constructor.
function readFilePromise(path) return new Promise((resolve, reject) => readFile(path, (err, data) => if (err) reject(err); > resolve(data); >); >); > try const data = await readFilePromise("foo.txt"); console.log(data); > catch (err) console.error(err); >
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Jun 19, 2023 by MDN contributors.
Your blueprint for a better internet.
TypeError() constructor
The TypeError() constructor creates TypeError objects.
Syntax
new TypeError() new TypeError(message) new TypeError(message, options) new TypeError(message, fileName) new TypeError(message, fileName, lineNumber) TypeError() TypeError(message) TypeError(message, options) TypeError(message, fileName) TypeError(message, fileName, lineNumber)
Note: TypeError() can be called with or without new . Both create a new TypeError instance.
Parameters
Human-readable description of the error
An object that has the following properties:
A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error.
fileName Optional Non-standard
The name of the file containing the code that caused the exception
lineNumber Optional Non-standard
The line number of the code that caused the exception
Examples
Catching a TypeError
try null.f(); > catch (e) console.log(e instanceof TypeError); // true console.log(e.message); // "null has no properties" console.log(e.name); // "TypeError" console.log(e.stack); // Stack of the error >
Creating a TypeError
try throw new TypeError("Hello"); > catch (e) console.log(e instanceof TypeError); // true console.log(e.message); // "Hello" console.log(e.name); // "TypeError" console.log(e.stack); // Stack of the error >
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on May 26, 2023 by MDN contributors.
Your blueprint for a better internet.
TypeError
The TypeError object represents an error when an operation could not be performed, typically (but not exclusively) when a value is not of the expected type.
A TypeError may be thrown when:
- an operand or argument passed to a function is incompatible with the type expected by that operator or function; or
- when attempting to modify a value that cannot be changed; or
- when attempting to use a value in an inappropriate way.
Constructor
Creates a new TypeError object.
Instance properties
Error message. Although ECMA-262 specifies that TypeError should provide its own message property, in SpiderMonkey, it inherits Error.prototype.message .
Error name. Inherited from Error .
Path to file that raised this error. Inherited from Error .
Line number in file that raised this error. Inherited from Error .
Column number in line that raised this error. Inherited from Error .
Stack trace. Inherited from Error .
Examples
Catching a TypeError
try null.f() > catch (e) console.log(e instanceof TypeError) // true console.log(e.message) // "null has no properties" console.log(e.name) // "TypeError" console.log(e.fileName) // "Scratchpad/1" console.log(e.lineNumber) // 2 console.log(e.columnNumber) // 2 console.log(e.stack) // "@Scratchpad/2:2:3\n" >
Creating a TypeError
try throw new TypeError('Hello', "someFile.js", 10) > catch (e) console.log(e instanceof TypeError) // true console.log(e.message) // "Hello" console.log(e.name) // "TypeError" console.log(e.fileName) // "someFile.js" console.log(e.lineNumber) // 10 console.log(e.columnNumber) // 0 console.log(e.stack) // "@Scratchpad/2:2:9\n" >