Comp 110 Throwing Errors

Throwing Errors

When dealing with functions, we often run into illogical cases. We can address these by "throwing an Error" with an error message that describes the problem:

throw new Error("Error message");

For example, if I want to deal with the illogical case of trying to access the fifth element in a List that's only four elements long, I might throw this Error:

throw new Error("Cannot access an element beyond the length of the List");

Throwing an Error causes the program to stop and display the error message you provide.