Day 14 Of #30DaysOfJavaScript

Day 14 Of #30DaysOfJavaScript

ยท

2 min read

Introduction

Hey folks, I hope that you must have read my Day 13 Article on #30DaysOfJs. In case, if you haven't then make sure you give it a read by clicking here.

Error Handling

While writing code you might encounter different types of errors. To solve them efficiently it is important to understand the type of error you're getting.

JavaScript provides a try-catch-finally block to catch all the errors that you encounter.

try {
  // Error may occur
} catch (err) {
  // Error occurs
} finally {
  // Code which has to be executed
}

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

catch*-* The catch block can have parameters that will give you error information. Catch block is used to log an error or display specific messages to the user.

finally*-* The finally block can be used to complete the remaining task or reset variables that might have changed before the error occurred in the try block.

For Example-

try {
  let lastName = 'Kapur'
  let fullName = fistName + ' ' + lastName
} catch (err) {
  console.log(err)
}

// Output --> 
// ReferenceError: fistName is not defined
//    at <anonymous>:4:20

throw- The throw statement allows us to create a custom error. We can through a string, number, boolean or object use the throw statement to throw an exception. When you throw an exception, the expression specifies the value of the exception. Each of the following throws an exception:

throw 'Error' // Generates an exception with a string value
throw true // Generates an exception with the value true
throw new Error('Bug') // Generates an error object with the message of Required

Error Types

  • ReferenceError- A ReferenceError is thrown if we use a variable that has not been declared.

For Example-

let firstName = 'Shivank'
let fullName = firstName + ' ' + lastName
console.log(fullName)

// Output -->
// Uncaught ReferenceError: lastName is not defined
//    at <anonymous>:2:35
  • SyntaxError- A SyntaxError is thrown if a syntax error occurs.

For Example-

let cube = 2 x 2 x 2
console.log(cube)
console.log('Hello world")

// Output -->
// Uncaught SyntaxError: Unexpected identifier
  • TypeError- A TypeError is thrown if a type error occurs.

For Example-

let num = 34
console.log(num.toUpperCase())

// Output -->
// Uncaught TypeError: num.toLowerCase is not a function
//    at <anonymous>:2:17

I hope that you must have found this article quite helpful. If yes, then do give a read to some of my other articles!

Who knows you might become a great programmer ๐Ÿค”!

ย