V
V
vaniapooh2012-05-26 13:01:36
JavaScript
vaniapooh, 2012-05-26 13:01:36

Javascript try..catch?

In Javascript , according to the specification, there is such a construct as try..catch . I have been writing the client side in Javascript for a long time (but this is not my main language) and I have practically never seen such blocks used anywhere on the client side. The question is - in what cases is the use of such a block justified and what are the possible limitations (associated, for example, with the difference in Javascript implementation in different browsers)? How much is needed when writing server-side Javascript?

Answer the question

In order to leave comments, you need to log in

9 answer(s)
K
Konstantin Kitmanov, 2012-05-26
@k12th

If you submit invalid JSON to JSON.parse, it will throw an exception. This is where try..catch comes in handy.

A
Anatoly, 2012-05-26
@taliban

Do not listen to the nonsense above, in javascript, as in any other language, you need to use try ... catch. Threads are not immune from errors, and this block will at least show the user that an unknown / such and such an error has occurred. personally, I often use try as a return from methods/functions, because it is not always convenient to make a chain of returns, and sometimes situations arise that further continuation is not necessary.
the same ajax yes, this is a great example, incorrect data came
in, you can also use it for your errors in libraries (large popular libraries actively use it)

S
Sergey, 2012-05-26
Protko @Fesor

On the client side, try/catch are rarely used, because exception situations are associated with non-existent methods/variables/properties. But if we are talking about, say, working with files or something else, they can be useful. Also useful.
Alas, I didn’t work much with server-side JS, but when I was dealing with it, or rather choosing between Erlang and Node.js, I came across an article that everything in Node.js should be wrapped in try / catch. This is due to the fact that if something falls, and the situations are different, then the entire server will fall. And it certainly won't make you happy.

N
norlin, 2012-05-28
@norlin

IMHO, any try-catch (at least in javascript) is a fight against the effect, not the causes. There is an error - it is necessary to fix it, and not hide it from the user.
There is an asynchronous \ file method - it is necessary to equally process both successful execution and if something went wrong.
For example, in node.js, you can hang an event on an “uncaught exception” - useful in combat conditions when the server should not crash despite an error.
But this is just a testing tool. That is, there was an error - they wrote it down in the log - they saw it - they fixed it.

M
mayhem, 2012-05-26
@mayhem

if you use throw Error("message") in your libraries to return an error, then try ... catch will have to :)

B
Boris Chumichev, 2014-05-10
@BorisChumichev

In both browser and server-side Javascript, the try/catch construct is used to catch exceptions in synchronous operations (example: deserializing JSON data or validating data entered by the user). If you want to handle errors in asynchronous operations, then the error is either passed to the callback function (In Node.js, the common pattern for calling a callback function is callback(err, results), where only one of the arguments can be non-null.) , or in more complex cases, the 'error' event of the EventEmitter class object is generated.
Node.js uses try/catch veryrarely (mostly only when parsing JSON data), this is due to the fact that most operations in Node.js are asynchronous, as a rule, an error is passed to a callback function or an "error" event is generated on an object of the EventEmitter class.
Here is an example illustrating that try/catch will not catch an exception thrown while performing an asynchronous operation:

function myApiFunc(callback)
{
  /*
   * Пример некорректного перехвата исключений
   * в асинхронных операциях
   */
  try {
    doSomeAsynchronousOperation(function (err) {
      if (err)
        throw (err);
    });
  } catch (ex) {
    callback(ex);
  }
}

The fact is that an exception is thrown and, accordingly, should be caught in the context in which the function is called . In this example, try/catch and the call to the function that throws the exception will be executed in different contexts due to the asynchrony of the doSomeAsynchronousOperation function.

K
ksdaemon, 2012-05-26
@ksdaemon

I agree with the first comment: the most logical place where you want to use try / catch is, for example, wrapping requests through Ajax to the server, but in the XmlHttpRequest object, and not only there are special methods like onerror , in which, if necessary, you can implement the processing of incorrect responses . So here the use of try/catch loses its meaning. So it's probably a mechanism to use if you're just used to writing with custom exceptions. That is, for example, checking the form for the validity of the data - you check, you find an error, you throw an exception yourself, you yourself catch it and process it.
It might make sense to use try/catch when trying to use some of the things available in modern browsers, and fallback to something simple if they aren't there.

E
egorinsk, 2012-05-27
@egorinsk

I wrapped event handlers, setInterval/setTimeout calls, and callbacks in try/catch (of course not by hand) to catch errors and log to the server. This, in my opinion, is the only use, since under normal conditions the code does not throw exceptions (in fact, that's why they are called exceptions).

D
dmsx, 2013-02-26
@dmsx

try catch can be used not only to catch random bugs related to the curvature of the developer's hands, but also to catch exceptions where we cannot be completely sure that everything will be ok in a given section of code, but also as a tool when designing complex applications, generating exceptions on its own and catching them at different levels.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question