try...catch blocks are generally encourages to be used less, and this doesn't depend on the language you use.
The main reason for this is the cost of catch blocks. Also another reason is that, when you wrap many statements with a single try...catch block, in catch block you can't be sure what was exactly the main problem.
It's better to use techniques like input validation or if...else blocks to reduce the probability of an exception (error) to happen. For example, when you want to work with a number which is taken from user, instead of using try...catch, you can use:
if (isNaN(numberVariable))
{
alert('you should enter a valid number');
}
Answer from Saeed Neamati on Stack OverflowVideos
try...catch blocks are generally encourages to be used less, and this doesn't depend on the language you use.
The main reason for this is the cost of catch blocks. Also another reason is that, when you wrap many statements with a single try...catch block, in catch block you can't be sure what was exactly the main problem.
It's better to use techniques like input validation or if...else blocks to reduce the probability of an exception (error) to happen. For example, when you want to work with a number which is taken from user, instead of using try...catch, you can use:
if (isNaN(numberVariable))
{
alert('you should enter a valid number');
}
I found this from a post here:
When Should You Use try-catch?
The try-catch statement should be used any time you want to hide errors from the user, or any time you want to produce custom errors for your users’ benefit. If you haven’t figured it out yet, when you execute a try-catch statement, the browser’s usual error handling mechanism will be disabled.
You can probably see the possible benefits to this when building large applications. Debugging every possible circumstance in any application’s flow is often time consuming, and many possibilities could be inadvertantly overlooked. Of course, with proper bug testing, no area should be overlooked. But the try-catch statement works as a nice fallback in areas of your code that could fail under unusual circumstances that were not foreseen during development.
Another benefit provided by the try-catch statement is that it hides overly-technical error messages from users who wouldn’t understand them anyhow.
The best time to use try-catch is in portions of your code where you suspect errors will occur that are beyond your control, for whatever reasons.
When Should try-catch be Avoided?
You shouldn’t use the try-catch statement if you know an error is going to occur, because in this case you would want to debug the problem, not mask it. The try-catch statement should be executed only on sections of code where you suspect errors might occur, and due to the overwhelming number of possible circumstances, you cannot completely verify if an error will take place, or when it will do so. In the latter case, it would be appropriate to use try-catch.
Hello,
I am taking a udemy course on JavaScript. In the Catching and Throwing Errors lesson, the teacher introduces us to Try/Catch block. My first remark was, why would someone write an alternative if his code didn't work while he supposed to find the source of the problem. When I searched in Stackoverflow and Quora, they almost agreed on the rule of 'use as less as possible'. And because of that, I'm wondering, How often do you use in real world projects?
Thank you so much!
You should only catch when you can actually do something to resolve the error.
So, you normally always catch, or otherwise handle exceptions at the top level, because you want to log or display the error somehow even if you can't resolve it.
Don't just put catch { throw } in all your functions, let the exception bubble up.
I would put a catch in functions for something like...
try
{
//load data over dodgy IR connection
}
catch(TransmissionException)
{
//retry because we expect exceptions and know they are temporal
}
Or this
try
{
//something complicated
}
catch
{
throw //don't know what to do with errors but need a catch syntactically
}
finally
{
//need to do some clean up
}
But not:
SavetoDisc()
{
try
{
//write to disc
}
catch(RunOutOfDiscSpace e)
{
//log an error (to disc?)
throw //only using catch block to log
}
}
Main()
try
{
SaveToDisc()
}
catch
{
//log the error!
throw (again?)
}
One() and Two() catch blocks would essentially just terminate the function and log a message that something went wrong.
This is almost never what you want to do. Normally, when you call a function you either are expecting a result or you are expecting some sort of side-effect (or both.) When you just log and exit it creates issues in both scenarios.
If your function returns a value, you need to return something to the caller. There's an alternative to exceptions using a return value that may represent an error but I'm going to ignore that option in this answer. So generally, you'll end up returning null or some other non-answer. Now you need to accommodate the possibility of this in every call to a function that might terminate abnormally. This tends to be a mess and often becomes a source of defects.
If there's some expectation of some side-effect, it's usually the case that later steps in your application depend on that being completed. If you just exit the function when something goes wrong, your caller will not have any indication that it didn't happen. In practice this means something else fails later, or worse, something happens later that puts your things into an invalid state.
The concept of an exception is that it's an alternative path to execution flow. As an analogy, let's say you are writing a function that engages the landing gear of a plane. What do you do if the doors don't open? You don't just exit and log to the flight recorder so that the cleanup crew can find it. It's important that the landing gear sequence stops and this problem reported back to the cockpit so that the pilots can do something about it. It doesn't really matter which way it failed, you want to do the same thing: signal that there was an issue and what is known about it regardless of which function in that sequence failed.
This brings us back to ewan's answer. Don't catch exceptions that you can't resolve. Doing so defeats the purpose. The point is to let them bubble up to a point in your application where they can be handled appropriately. Often that means exiting abnormally and displaying an error message. By halting that bubble up routine prematurely, you aren't helping anyone, it just makes things worse.
One should avoid throw errors as the way to pass error conditions around in applications.
The throw statement should only be used "For this should never happen, crash and burn. Do not recover elegantly in any way"
try catch however is used in situation where host objects or ECMAScript may throw errors.
Example:
var json
try {
json = JSON.parse(input)
} catch (e) {
// invalid json input, set to null
json = null
}
Recommendations in the node.js community is that you pass errors around in callbacks (Because errors only occur for asynchronous operations) as the first argument
fs.readFile(uri, function (err, fileData) {
if (err) {
// handle
// A. give the error to someone else
return callback(err)
// B. recover logic
return recoverElegantly(err)
// C. Crash and burn
throw err
}
// success case, handle nicely
})
There are also other issues like try / catch is really expensive and it's ugly and it simply doesn't work with asynchronous operations.
So since synchronous operations should not throw an error and it doesn't work with asynchronous operations, no-one uses try catch except for errors thrown by host objects or ECMAScript
Try/catch in Javascript is not as bullet-proof as in other languages, due to Javascript's asynchronous nature. Consider this snippet:
try {
setTimeout(function() {
do_something_that_throws();
}, 1000);
}
catch (e) {
alert("You won't see this!");
}
The problem is that the control flow leaves the try block before do_something_that_throws() gets executed, so the error thrown inside the callback never gets catched.
So try/catch is basically inappropriate in many cases, and it's not always obvious whether something executes code asynchronously or not. Fortunately, javascript with its peculiar single-threaded-asynchronous-callback idiom and its support for actual closures provides an elegant alternative: continuation-passing style error handling. Just pass the proper response to any error as a function, e.g.:
setTimeout(function () {
do_something_that_calls_err(function(err) {
alert("Something went wrong, namely this: " + err);
}),
1000);