Platformer Example

Imagine you are building a platformer game, and you have a player character that can jump and move around the game world. The player character has a jump() function that allows it to jump, and this function may throw an error if the player tries to jump while they are already in the air.

Here is an example of how you could use the try...catch statement to handle this error:

class Player {
  constructor() {
    this.x = 0;
    this.y = 0;
    this.isJumping = false;
  }

  jump() {
    if (this.isJumping) {
      throw new Error('Cannot jump while in the air');
    }
    this.isJumping = true;
    // code to make the player jump
  }
}

const player = new Player();

document.addEventListener('keydown', event => {
  if (event.key === 'Space') {
    try {
      player.jump();
    } catch (error) {
      console.error(error);
    }
  }
});

In this example, the Player class has a jump() function that throws an error if the player is already in the air (this.isJumping is true). The try...catch statement is used in an event listener that is triggered when the player presses the space bar. If the player tries to jump while they are already in the air, the error will be thrown and caught by the catch block, which will log the error to the console. If the player is not in the air, the jump() function will be executed and the player will jump.

Using the try...catch statement in this way allows you to handle errors in a controlled way, rather than allowing them to crash the game. You could also use the finally block to execute code after the try and catch blocks, such as resetting the player's isJumping status or displaying a message to the player.

Last updated