In Python, you can catch a specific exception like this:
try :
[1, 2, 3][4]
except IndexError:
print("uhhh index is out of range pls fix it lmao")
How do I achieve the same thing in JavaScript? I tried this:
class NegativeIntegerError extends Error {
constructor(message: string) {
super(message)
this.message = message
}
}
class NegativeRangeNotSupportedError extends Error {
constructor(message: string) {
super(message)
this.message = message
}
}
export function range(start: number, stop: number, step: number = 1): number[] {
if (start < 0 || stop < 0 || step < 0) {
throw new NegativeRangeNotSupportedError("Negative range start, stop, or step is not supported for now. Please use a positive range.")
}
let res: number[] = []
for (let index: number = start; index <= stop; index += step) {
res.push(index)
}
return res
}
export function getDivisors(number: number): number[] {
try {
return range(1, number).filter((element) => (number % element == 0))
} catch (message: any | unknown) {
if (message.includes("error TS119: Expression Expected."))
throw new NegativeIntegerError("Could not get divisors of a negative number.")
else
console.log("there is nothing to cause an error what")
}
}
but I get the error message "message.includes" is not a function
. Is there an another way to handle a specific exception?
New contributor
Lanzoor is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1