Exceptions
When a function is not working correctly, what we would typically want to happen is this case, is that the function stops it’s normal flow and goes in another flow that knows much on how to handle the problem.
Exceptions are what makes it possible for a function to run while there is a problem, and still proceed in a predictable path that we specified, By throwing an exception that we specified, which will not only propagate outside the function, but also up to the first caller of the function, unless we catch the thrown error.
The fact that you can catch an exception from a given point in your program while it’s propagating upward, make it even easier to determine your predicted path of failure.
To catch an exception you would use the try
and catch
block with the throw
keyword. The try block, as the name implied, tries the codes to be executed and throws an error in case there is any.
Using the catch
block , that receives a parameter of your actual error you can handle your thrown exception gracefully.
You can also use the throw
keyword to throw your custom errors and still use the catch block to catch these specific errors.
Unhandled Exceptions
When you don’t handle your exceptions correctly, they usually propagate to the top level of the program and handled automatically by the environment you are running into.
- If you are in the browser then the engine will handle the exception and logs the result to the browser console.
- If you are in the node environment, exceptions are taken much more seriously, the process will simply crash and this would be a clear signal that something went wrong.
When catching errors, you might be tempted to only handle the patch that you predicted and us the catch block to work with the error as if it was your prediction, this might lead to more problem as for you might end up working with error that you think are your predicted errors yet they are in fact other errors. It’s often a good practice to first check if the error you are working with is the one you are indeed expecting before continuing.