• ¿Documento equivocado? Cámbialo gratis
  • Escrito por estudiantes que aprobaron
  • Inmediatamente disponible después del pago
  • Leer en línea o como PDF
Vender
¿Dónde estudias?
Tu idioma
Document preview thumbnail
Vista previa 2 fuera de 6 páginas
Otro

Error Handling in JavaScript: A Beginner’s Guide with Examples

Document preview thumbnail
Vista previa 2 fuera de 6 páginas

This document covers error handling in JavaScript, including how to use try-catch blocks, throwing exceptions, and working with JavaScript error objects. Learn how to catch and handle errors to write more reliable and robust code.

Vista previa del contenido

Error Handling in JavaScript
Error handling in JavaScript allows developers to manage unexpected conditions
in a program gracefully, ensuring that the application continues running smoothly
and providing useful feedback to the user.

1. Types of Errors
JavaScript has several types of errors, which can be broadly categorized as:

 Syntax Errors: Occur when the code violates JavaScript's grammar rules.

const name = "John' // SyntaxError: Unexpected token

 Reference Errors: Occur when trying to reference a variable that is not
defined.

console.log(nonExistentVar); // ReferenceError: nonExistentVar is not
defined

 Type Errors: Occur when a value is not of the expected type.

null.foo(); // TypeError: Cannot read property 'foo' of null

 Range Errors: Occur when a value is out of range.

let numbers = new Array(-1); // RangeError: Invalid array length

 Eval Errors: Occur when using the eval() function inappropriately.

eval('alert("test")'); // EvalError: Invalid or illegal use of eval()



2. Try...Catch
The try...catch statement allows you to test a block of code for errors and handle
those errors gracefully.

, Syntax:

try {
// Code that may throw an error
} catch (error) {
// Code that handles the error
}

Example:

try {
const result = someUndefinedFunction();
} catch (error) {
console.log("An error occurred: " + error.message);
}

 try block: Contains the code that may cause an error.
 catch block: Contains the code that handles the error, typically logging the
error message or providing a fallback behavior.
 The catch block receives an Error object, which has properties like name,
message, and stack.

Handling Specific Errors:

You can catch specific types of errors by checking the name property of the error
object.

try {
const result = someUndefinedFunction();
} catch (error) {
if (error instanceof ReferenceError) {
console.log("Reference Error: " + error.message);
} else {
console.log("An unexpected error occurred: " + error.message);
}
}

Información del documento

Subido en
27 de enero de 2025
Número de páginas
6
Escrito en
2024/2025
Tipo
Otro
Personaje
Desconocido
$7.39

¿Documento equivocado? Cámbialo gratis Dentro de los 14 días posteriores a la compra y antes de descargarlo, puedes elegir otro documento. Puedes gastar el importe de nuevo.
Escrito por estudiantes que aprobaron
Inmediatamente disponible después del pago
Leer en línea o como PDF

Vendido
0
Seguidores
0
Artículos
252
Última venta
-




Por qué los estudiantes eligen Stuvia

Creado por compañeros estudiantes, verificado por reseñas

Calidad en la que puedes confiar: escrito por estudiantes que aprobaron y evaluado por otros que han usado estos resúmenes.

¿No estás satisfecho? Elige otro documento

¡No te preocupes! Puedes elegir directamente otro documento que se ajuste mejor a lo que buscas.

Paga como quieras, empieza a estudiar al instante

Sin suscripción, sin compromisos. Paga como estés acostumbrado con tarjeta de crédito y descarga tu documento PDF inmediatamente.

Student with book image

“Comprado, descargado y aprobado. Así de fácil puede ser.”

Alisha Student

Preguntas frecuentes