🖥️Exception Handling

All about Exception Handling shortcut.

Equip Safurai with the capacity to anticipate, identify, and respond to issues within your code. By crafting a resilient error-handling structure, you can minimize the potential disruptions and instabilities in your software, making it robust and reliable.

Request: Integrate a try/catch error handling structure into the following code:

Safurai suggestion:

Certainly! Here's the modified code with try/catch error handling structure:

function displaySelection(player, selection, result) {
  try {
    if (player === 'player') {
      playerSelect.innerHTML = `<i class="fas fa-hand-${selection}"></i>`;
      if (result === "Player won!") {
        playerSelect.style.color = 'green';
        compSelect.style.color = 'red';
      }
    } else {
      compSelect.innerHTML = `<i class="fas fa-hand-${selection}"></i>`;
      if (result === "Computer won!") {
        compSelect.style.color = 'green';
        playerSelect.style.color = 'red';
      }
    }
    if (result === 'Draw!') {
      compSelect.style.color = '';
      playerSelect.style.color = '';
    }
  } catch (error) {
    console.log(error);
  }
}

function scoreBoard(result) {
  try {
    if (result === "Player won!") {
      playerScore++;
      pScore.innerText = playerScore;
      cScore.innerText = computerScore;
    } else if (result === "Computer won!") {
      computerScore++;
      pScore.innerText = playerScore;
      cScore.innerText = computerScore;
    } else {
      return false;
    }
  } catch (error) {
    console.log(error);
  }
}

I've added try blocks to both functions and catch blocks to handle any errors that may arise during execution. If an error occurs, it will be logged to the console.

Last updated