Day 14. Error Handling

On Day 14, I learned about some error handling mechanisms that allows me to test-run the codes see if they have any errors.

header image TIL


Error Handling

JavaScript is a loosely-typed language. When I try to access an undefined variable, call undefined function, or etc, I will get a runtime error. JavaScript provides an error-handling mechanism to catch runtime errors, using try-catch-finally block.

try {
  // code that may throw an error
} catch(err) {
  // code to be executed if an error occurs
} finally {
  // code to be executed regardless of an error occurs or not
}

1. try

It wraps suspicious code that may throw an error in the block. try statement allows us to define a block of code to be tested while it is being executed.

2. catch

In the catch block, I write the code to be executed when an error occurs. It is used to log an error or display specific messages to the user.

catch block takes a parameter that will give error information. It is common to pass ‘e’, ‘err’, or ‘error’ as a parameter. This parameter is an object, and it has name and message keys.

3. finally

finally block will be always executed, whether an error occurs or not. It can be used to complete the remaining task, or reset variables that might have changed before the error that occured in try block.

try {
  let lastName = 'Doe'
  let fullName = firstName + ' ' + lastName
} catch (err) {
  // console.error() can also be used
  console.log(err);
} finally {
  console.log('I am always executed.');
}
/*
  ReferenceError: firstName is not defined
      at <anonymous>:3:18
  I am always executed.
*/
try {
  let firstName = 'Ramona';
  let fullName = firstName + ' ' + lastName;
} catch (err) {
  console.log('Name of the error:', err.name);
  console.log('Error message:', err.message);
} finally {
  console.log('I am always executed.');
}

/*
  Name of the error: ReferenceError
  Error message: lastName is not defined
  I am always executed.
*/


4. throw

throw expression;

throw statement allows to create a cumtom error. I can throw a string, number, boolean or an object. When I throw an exception, the expression specifies the value of the exception.

throw 'Error2'  // Uncaught Error2

const throwErrorExample = () => {
  let message
  let x = prompt('Enter a number: ');
  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) {
    console.log(err);
  }
}

throwErrorExample()


I can specify an object when I throw an exception. Then I can reference the object’s properties in the catch block. The example below creates an object of type UserException and uses it in a throw statement.

function UserException(message) {
  this.message = message;
  this.name = 'UserException';
}
function getMonthName(mo) {
  // Adjust month number for array index
  mo = mo - 1;
  let months = [
    'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
    'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  if (months[mo] !== undefined) {
    return months[mo];
  } else {
    // throw an object
    throw new UserException('Invalid Month');
  }
}

console.log(getMonthName(3));  // 'Mar'
console.log(getMonthName(15));
/* 
  Uncaught 
  UserException {message: 'Invalid Month', name: 'UserException'}
*/


try {
  // statements to try
  // 15 is out of bound to raise the exception
  let myMonth = 15;
  let monthName = getMonthName(myMonth);
} catch (e) {
  monthName = 'unknown';
  // pass exception object to err handler
  console.error(e.message, e.name);
}

// Invalid Month UserException


5. Error Types

A ReferenceError is thrown if I use a variable that has not been declared.

let a = 50;
let c = 12;

console.log(a + b);
// Uncaught ReferenceError: b is not defined


A syntax error has occured.

let square = 2 x 2;  // should be 2*2 for calculation
console.log(square);
// Uncaught SyntaxError: Unexpected identifier

console.log('Hello, world");
// Uncaught SyntaxError: Unexpected identifier


A type error has occured.

const abc = ['a', 'b', 'c'];

console.log(abc.toUpperCase());
// Uncaught TypeError: abc.toUpperCase is not a function


Leave a comment