Javascript - throw for Custom Errors
Code Life
By Pierre Marsaa
Raising Your Own Error with throw
Suppose you write a heal(hp, amount) function, and someone calls it with a negative number (-30).
JavaScript sees nothing wrong with 50 + (-30), so the Codémon silently loses HP instead of healing:
↗️
Loading editor...
↶
↷
JavaScript doesn't know the rules of your game — you do! The throw keyword lets you raise an error yourself as soon as a rule is broken:
↗️
Loading editor...
↶
↷
Now heal(50, -30) stops immediately with your custom error message, right where the mistake happened!
Verify