Creating an Exception

This lesson introduces how to work with exceptions.

Throwing exceptions

TypeScript follows ECMAScript in terms of the exception. You can throw a new exception by using the keyword throw followed by an instance of the exception you desire. It’s always better to throw an object instead of a string. The reason is that throwing an object comes with a whole execution stack since the object must inherit from the base interface Error. The interface Error defines a name, a message, and the stack. The only case where you do not need to throw an instance of an exception is when using the ErrorConstructor which lets you throw the error directly by using throw Error("Message here that is optional").

Press + to interact
function throw1() {
throw "error in string";
}
function throw2() {
throw Error("Message Here");
}
function throw3() {
const err: Error = new Error("Message Here");
throw err;
}
// throw1();
// throw2();
// throw3();

The code above has three lines commented. The first one, line 14, returns a string. When thrown, the output ...