+ 1
what is try catch ..finally block in javascript?
Please give an example that explains try catch ..finally code block in javascript. Thanks
5 Answers
+ 1
I'm not sure how to use them in JavaScript, but I have good understanding on try-except-finally in Python.
Try-block often contains code that has a small risk to result in errors.
If an error appears, a catch-block might stop the error from terminating the program and runs its codeblock.
"might" because you can make catch to only handle specified errors.
For example you can make program print "Dumb programmer!" in case of syntax error and print "Dumb tester!" in case of zero division error (just an example, no zero division errors on js).
If an error appears and no catch block is specified to catch it, the error will terminate the program.
So shortly try-catch could be thought as "if an error appears in the code, run the backup code.".
Finally is a statement that is not affected by errors.
Its code will "always" be ran, whatever happened in the try-catch blocks.
This can be useful if you for example wanted to open a file and ensure it gets closed or other important things that should be done in end.
+ 1
(It is called error handling)
Anyways it is important to remember that try-catch-finally should not be overused because it will likely hide some significant errors making program harder to debug.
It is more recommended to use error handling for errors that are too difficult to avoid even though the program were otherwise quite clean (from bugs).
But an example where it would be used:
If an IDE crashed (likely by an error) if almost whole IDE program was written in try-block of a try-finally, there could have been code that automatically saved the program if the program terminates (by crash or purpose) and in case of crash it would have a programmer's day, or life.
0
try{
// some code for trial
// if an error occurs
}
Catch
{
// catch those errors
// continue the program
}
finally
{
// run this code
}
The above example is correct but
Is there a working example that you can provide.
0
hi @Seb TheS
thanks for the textual answer