JAVASCRIPT:  notes about Exception Handling

JAVASCRIPT: notes about Exception Handling

In Javascript an Error object is generated :

  • when at runtime the engine notices something is going wrong and can't continue executing your code ( different error types are natively known to the Javascript engine, as SyntaxError or TypeError)
  • when , in a particular situation and for a particular reason, yourself as a developer decide to halt the execution of your code and want to raise a custom exception

The Error object is created by the Error class constructor . https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error

const err = new Error("Something wrong!");

The basic Error object presents 2 main properties:

  • message: the error message.
  • name: the error's type (default: "Error")


Custom errors

For a better and tailored error handling we can create custom error objects:
they can have specific properties on their own, but, at the same time, they usually inherit generic properties from the base Error class

class MyPippoError extends Error {
  constructor(message) {
    super(message);
    this.name = "MyPippoError";
  }
}

The parent costructor ("super") do us the favor to set the "message" property ( it's a property we inherit from Error).
The parent constructor sets the "name" property too , but we override it with our own custom name ("MyPippoError")


Throw and Catch

We can throw any exception (custom or not) with the throw keyword.

And we can deal with any exception (custom or not) with the try/catch statement, which "tries" to execute a block of code and, if necessary, "catches" the potential raised exceptions.

try/catch statement must not be abused: it should be especially used in portions of code where potential errors are beyond your control, for example network errors when you're calling an API, or parsing errors when you're dealing with user inputs.

try {
/* anything you want */
} catch (err) {
  console.error ("Terrible Pippo Error " + err.message); 
  }

The catch block can deal with the exception and/or can itself re-throw it upwards in the stack.
Once an exception is thrown, it bubbles up in the call stack, until it is caught by some "higher" function. If nothing catches it, the application will crash.

Try/catch can have an optional "finally" block too:
it runs its instructions after try/catch has executed, regardless of whether some exceptions raised or not ( and regardless of whether the catch block itself has re-thrown an exception).
In the catch block we may need to catch only specific error classes too (recognizing them through the instanceof operator)

try {
  // anything you want
} catch (err) {
  if (err instanceof MyPippoError) {
    /* our custom MyPippoError class */
    console.error("Terrible Pippo Error " + err.message);
  } else if (err instanceof MyPlutoError) {
    /* another custom error class */
    console.error("Nasty Pluto Error " + err.message);
  } else if (err instanceof SyntaxError) {
    /* built-in SyntaxError class provided by Javascript */
    console.error("SyntaxError " + err.message);
  } else {
    throw err; /*  try/catch is not able to manage this error,  so I rethrow it to the "upper level" */
  }
} finally {
  console.log("At the end it's my turn");
}


Did I write anything wrong ? Or you have better ideas? Please share it in the comments :-)


Photo by Sarah Kilian on Unsplash