Throw InvalidArgumentException in a JavaScript method like one does in Java or similar languages.
I have been trying to familiarize myself with JavaSctipt error handling, and I know I can throw exceptions using the throw
keyword.
To achieve this, I read the throw documentation on MDN and the Error documentation on MDN as well.
So far this is my code:
if (mySize >= myArray.length)
throw new Error("InvalidArgumentExcpetion - BANG!!!!");
This code has some problems for me:
So now I am confused.
The throw statement throws a user-defined exception. Execution of the current function will stop (the statements after throw won't be executed), and control will be passed to the first catch block in the call stack. If no catch block exists among caller functions, the program will terminate.
To declare a function that throws an error, set its return type to never . The never type is used for functions that never return a value, in other words functions that throw an exception or terminate execution of the program.
After doing research, I now have come down to a solution that I like. Special kudos to Toan, I would gladly chose his answer, but since I do feel that it is still a little bit incomplete, I decided to create my own answer with my own findings. Hope it helps someone !
Using the solution proposed by Toan: https://stackoverflow.com/a/38146237/1337392
It is a possible, albeit if you want customization you do need to create your own object.
Thanks for all the help guys! kudos++ for all!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With