logo
logo

Exceptions Cheatsheet

What is an exception?

An exception is a kind of error that is thrown when something goes wrong in the execution of the program. In JavaScript, many built-in exceptions are thrown automatically when something unexpected happens. For example, when we try to call an array method on an object, it throws a type error.

How to throw an exception

To throw an exception in JavaScript, we use the
throw
statement followed by an expression containing the value to be thrown. Here is an example of throwing an error message:
throw new Error('This is an error message')
In the above example, we are throwing an error message using the
throw
statement followed by an expression containing the error message. When the program encounters the
throw
statement, it stops executing the program and shows the error message.

You can throw any expression, including a string, number, boolean, or object. Here are some examples of throwing different types of expressions:

throw 'This is a string'
throw 500
throw true
throw { name: 'My Exception', message: 'This is my custom exception' }

Handling exceptions using try-catch statement

We can handle exceptions using the
try-catch
statement. The
try
block contains the code that may throw an exception, and the
catch
block contains the code to handle the exception. Here is an example:
try {
  // code that may throw an exception
  throw new Error('This is an error message')
} catch (e) {
  // code to handle the exception
  console.log(e.message)
}
In the above example, we have wrapped the
throw
statement in a
try
block. If an exception is thrown, the
catch
block is executed, and the error message is logged to the console. The
catch
block takes an identifier
e
that represents the exception object.

Let's look at another example of using try-catch to handle an exception:

function checkIfNum(num) {
  if (isNaN(num)) {
    throw new Error('Not a number')
  }
  console.log('Yes, this is a number')
}

try {
  checkIfNum('abc')
} catch (e) {
  console.log(e.message)
}
In the above example, we have defined a function
checkIfNum
that throws an exception if the argument is not a number. We then call the function with a string argument 'abc' inside the
try
block. Since the argument is not a number, an exception is thrown, and the
catch
block is executed. The error message 'Not a number' is logged to the console.

Creating an object constructor using the try-catch statement

In JavaScript, we can create object constructors that take in a parameter and use it to set a value for the object. We can use the
try-catch
statement to handle any errors that may arise during this process. Here's an example of an object constructor that takes in a string and sets it as the value of the object:
function MyString(string) {
  try {
    if (typeof string === 'string') {
      this.value = string;
    } else {
      throw new Error('Value must be a string');
    }
  } catch (e) {
    console.log(e.message);
  }
}
In this example, we use
try-catch
to handle the case where the value passed into the constructor is not a string. If it's not a string, we throw an error with the message 'Value must be a string'. The
catch
block then logs the error message to the console.

Creating custom exceptions and handling them using try-catch statements

We can create custom exceptions in JavaScript by defining our own error constructor. Here's an example of a custom error constructor called
StringExceptionError
:
function StringExceptionError(value) {
  this.value = value;
  this.message = 'Must be a string';
  this.toString = function() {
    return this.value + ' ' + this.message;
  }
}
In this example, we define a new error constructor that takes in a value and sets a message. We also define a
toString
method that returns the value and message. This will allow us to log more descriptive error messages.
We can use this custom error constructor in our
MyString
constructor by throwing it in the
catch
block:
function MyString(string) {
  try {
    if (typeof string === 'string') {
      this.value = string;
    } else {
      throw new StringExceptionError(string);
    }
  } catch (e) {
    console.log(e.toString());
  }
}
In this example, we throw a
StringExceptionError
with the value passed into the constructor. We then catch the error and log its
toString()
value to the console.

Using the finally statement for cleanup code

The
finally
statement is used to run code after a
try-catch
block, regardless of whether an error occurred or not. Here's an example of using
finally
to log a message after running some code:
function example() {
  try {
    console.log('Hi');
    throw new Error('Test');
  } catch (e) {
    console.log(e);
    return true;
  } finally {
    console.log('Always runs');
  }
}
In this example, we log 'Hi' and throw an error in the
try
block. We catch the error and log it to the console, then return
true
. Finally, we log 'Always runs' to the console. The output will look like this:
Hi
Error: Test
Always runs

Understanding the interaction between return statements in try-catch and finally statements

If a
finally
statement is used, its
return
statement will override any other
return
statement in the function. Here's an example of a function with a
finally
statement that overrides the previous return statement:
function example() {
  try {
    console.log('Hi');
    throw new Error('Test');
  } catch (e) {
    console.log(e);
    return true;
  } finally {
    console.log('Always runs');
    return false;
  }
}

In this example, we log 'Hi' and throw an error in the try block. We catch the error and log it to the console, then return true. Finally, we log 'Always runs' to the console and return false. Because the finally block's return statement overrides the previous return statement, the function will always return false.

It's important to be aware of this behavior when using return statements in functions that include try-catch-finally blocks. Make sure to consider which return statement you want to use and where you want to place it in the function.