1 # Restrict what can be thrown as an exception (no-throw-literal)
3 It is considered good practice to only `throw` the `Error` object itself or an object using the `Error` object as base objects for user-defined exceptions.
4 The fundamental benefit of `Error` objects is that they automatically keep track of where they were built and originated.
6 This rule restricts what can be thrown as an exception. When it was first created, it only prevented literals from being thrown (hence the name), but it has now been expanded to only allow expressions which have a possibility of being an `Error` object.
10 This rule is aimed at maintaining consistency when throwing exception by disallowing to throw literals and other expressions which cannot possibly be an `Error` object.
12 Examples of **incorrect** code for this rule:
15 /*eslint no-throw-literal: "error"*/
26 var err = new Error();
28 // err is recast to a string literal
30 var err = new Error();
35 Examples of **correct** code for this rule:
38 /*eslint no-throw-literal: "error"*/
42 throw new Error("error");
44 var e = new Error("error");
48 throw new Error("error");
56 Due to the limits of static analysis, this rule cannot guarantee that you will only throw `Error` objects.
58 Examples of **correct** code for this rule, but which do not throw an `Error` object:
61 /*eslint no-throw-literal: "error"*/
71 throw new String("error");