In JavaScript, we can handle errors and exceptions using the try-catch statement. The try block contains the code that might throw an exception, while the catch block contains the code that handles the thrown exception.
Here's an example code snippet which demonstrates the usage of try-catch:
index.tsx303 chars11 lines
In the above example, the try block tries to convert a number to uppercase using the toUpperCase() method, which will throw an exception as this method is only defined for strings. The catch block receives the thrown exception object and logs it to the console.
We can also throw our own customized exceptions using the throw statement, as shown below:
index.tsx365 chars16 linesIn the above example, the divide() function throws a customized exception if the second argument is zero. We then use try-catch to handle this exception and log it to the console.
gistlibby LogSnag