[JavaScript] Error Handling

·

2 min read

[JavaScript] Error Handling

Error Handling

Error handling is the way of managing errors and dealing with unexpected situations in a software application.

Errors can be categorized into expected errors and unexpected errors, and when designing a typical application, it should be assumed that unexpected error situations are more likely to occur.

There is always a possibility of unexpected errors occurring in code written by programmers, and it is important to be prepared to handle such error situations at any time.

try-catch

To prevent errors from occurring on the server, we implement exception handling.

const users = ["Lee", "Kim", "Park", 2];

try {
  for (const user of users) {
    console.log(user.toUpperCase());
  }
} catch (err) {
  console.error(`Error: ${err.message}`);
}

// LEE
// KIM
// PARK
// Error: user.toUpperCase is not a function

throw

When intentionally causing an error

function withdraw(amount, account) {
  if (amount > account.balance)
    throw new Error("No remaining balance"); // function stops running
  account.balance -= amount; // not executed
    console.log(`Current balance: ${account.balance}`); // not executed
}

const account = { balance: 1000 };
withdraw(2000, account);

// Error: "No remaining balance"

finally

Executed regardless of whether an attempted write operation throws an error or not

function errorException(isThrow) {
  try {
    console.log('Resource allocated');
    if (isThrow) throw new Error();
  } catch (error) {
    console.log('Error arised');
  } finally {
    console.log('Resource deallocated');
  }
}

errorException(false);
// Resource allocated
// Resource deallocated - always executed
errorException(true);
// Resource allocated
// Error arised
// Resource deallocated - always executed