Par cet article sans JavaScript tutorial, Louis vous donne un point de vue d
- Demo
- Agrandir
- Recharger
- New window
Gratuit iPage h�bergement Web pour la premi�re ann�e MOMENT
Si vous �tes toujours � la recherche d'un fournisseur d'h�bergement Web fiable avec des tarifs abordables, pourquoi vous ne prenez pas un peu de temps pour essayer iPage, seulement avec $1.89/month, inclus $500+ Cr�dits suppl�mentaires gratuites pour le paiement de 24 mois ($45)?
Plus de 1.000.000 de clients + existisng peuvent pas avoir tort, vraiment vous n'�tes pas aussi! Plus important encore, lorsque vous enregistrez l'h�bergement web � iPage gr�ce � notre lien, nous allons �tre heureux de renvoyer un plein remboursement. C'est g�nial! Vous devriez essayer iPage h�bergement web GRATUITEMENT maintenant! Et contactez-nous pour tout ce que vous devez savoir sur iPage.
I don't consider myself an application developer. I think I have some knowledge of application design principles, but it's something I'd like to improve on, especially in the area of JavaScript and Ajax-driven applications.
One technique that I believe is quite helpful when developing high-powered JavaScript apps is the JavaScript try-catch
statement (also referred to as try-catch-finally
). I became familiar with try-catch
sometime last year, and although I haven't used it much, I found it could prove useful in a number of circumstances.
In this article, I'm going to describe what try-catch
is, how it can be used, and how it can help make web applications less annoying to users.
Basic Syntax and Definition
The try-catch
statement was introduced in ECMA-262, 3rd Edition as a way to handle exceptions, and its syntax is the same as in the Java programming language. Here is how a basic try-catch
statement looks:
try { // code that might cause an error goes here } catch (error) { // error message or other response goes here }
The try
portion is where you would put any code that might throw an error. In other words, all significant code should go in the try
section. The catch
section will also hold code, but that section is not vital to the running of the application. So, if you removed the try-catch
statement altogether, the section of code inside the try
part would still be the same, but all the code inside the catch
would be removed.
If any error occurs during the try
portion, the try
section is exited and the catch
section is executed. The catch
portion of the statement will receive a JavaScript object containing error information. The error
identifier is required, but can be any custom name you choose. For
example, the following would be the same as the previous code example:
try { // code that might cause an error goes here } catch (watermelon) { // error message or other response goes here }
In the above example, the "error" identifier has been changed to "watermelon", but will have the same results. Obviously, a name like "watermelon" would be counterproductive, but this simply serves to demonstrate that the name is flexible, but is required.
Outputting the Exact Error That Occurred
The error
object (or watermelon
object, depending on what you named it), has a property called message
that holds details about the error that occured. So, the following would be a practical way to output a custom error:
try { doSomething(); // this function doesn't exist } catch (error) { alert(error.message); }
If you run the code above, the browser will alert the message
"doSomething is not defined". The error object also defines a property
called name
that describes the error in a more technical
fashion, but I don't really see any practical use for it. Those two
properties are the only ones that are cross-browser compatible.
Different browsers offer custom properties, some of which could prove
useful, such as lineNumber
in Firefox. But generally, it's best to stick to using just the message
property, since it's the most compatible and practical one available.
The Optional "finally" Clause
The try-catch
statement also permits the inclusion of a finally
clause. The code inside the finally
section will run no matter what. This comes in handy because that is not true of the try
section. For debugging purposes (or other reasons) you may require a
certain section of code to execute, even if errors occur. Such code
should be placed in the finally
section. There is nothing that could occur in the try
section or in the catch
section that would prevent the finally
section from executing. Even if a different return
statement is placed in each section, only the last return
statement (the one in the finally
section) will actually "return".
Look at the following example:
function testReturn() { try { return "bananas"; } catch (error) { return "oranges"; } finally { return "watermelons"; } } alert(testReturn());
Although it seems the alert
message should say "bananas" (because there is no error), it will actually output "watermelons", because the finally
clause always executes, regardless of any errors. Of course, this only happens because of the nature of the return
statement. The try
section would still execute, but the return
of the try
would be overriden by the return of the finally
clause.
Here is the same code, slightly modified:
function testReturn() { try { alert("bananas"); } catch (error) { return "oranges"; } finally { return "watermelons"; } } alert(testReturn());
Now the output will be two alert
statements. The first one is "bananas", the second is "watermelons". To prevent any problems resulting from overridden return
statements, make sure your try
and finally
clauses don't both contain return
statements, otherwise only the finally
return will actually be "returned".
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
.
Are There Performance Issues with try-catch
?
The short answer seems to be yes, although this article on MSDN says that performance is affected only when the catch
portion actually executes. This response to that article suggests otherwise.
An article on the Opera Developer Community says that try-catch-finally
should be avoided inside performance critical functions.
Finally, there is a good, but limited, in relation to performance, in Nicholas Zakas' new book, High Performance JavaScript.
I can't say for certain which view is correct, but as long as you use it in the most appropriate circumstances, performance hits will likely be kept to a minimum.
Overall, try-catch
is a useful statement and can come
in handy in a number of circumstances - especially when creating large
applications that could potentially create situations that are beyond a
developer's control.
- Sent (0)
- Nouveau
Générez vos vidéos d'entreprise par l'IA avec la voix ou simplement du texte
chatGPTaz.com
Parlez à ChatGPT dans votre langue maternelle
AppAIVidéo
Votre première application vidéo AI GRATUITE
Deepfake Video
Deepfake AI Video Maker
Deepfake
Deepfake AI Video Maker
AI Deep Fake
Deepfake AI Video Maker
AIvidio
AI Video Mobile Solutions
AIvideos
AI Video Platform & Solutions
AIvedio
AI Video App Maker
Faceswap AI en ligne
Échangez des visages, des vidéos, des photos et des GIF instantanément avec de puissants outils d'IA - Faceswap AI Online GRATUIT
Faceswap AI en ligne
Échangez des visages, des vidéos, des photos et des GIF instantanément avec de puissants outils d'IA - Faceswap AI Online GRATUIT
Temu gratuit 500 $ pour les nouveaux utilisateurs
Claim Free Temu $500 Credit via Affiliate & Influencer Program
Crédits publicitaires TikTok gratuits
Maîtrisez les publicités TikTok pour le marketing de votre entreprise
Dall-E-OpenAI.com
Générez automatiquement des images créatives avec l'IA
chatGPT4.win
Parlez à ChatGPT dans votre langue maternelle
Premier produit d'intelligence artificielle d'Elon Musk - Grok/UN.com
Parlez au chatbot Grok AI dans votre langue
Outily.win
Centre d'outils ouvert et gratuit, utilisable par tous et pour tous, avec des centaines d'outils
GateIO.gomymobi.com
Airdrops gratuits à réclamer et à partager jusqu'à 150 000 $ par projet
iPhoneKer.com
Économisez jusqu'à 630 $ à l'achat d'un nouvel iPhone 16
Acheter le robot Tesla Optimus
Commandez votre robot Tesla Bot : Optimus Gen 2 dès aujourd'hui pour moins de 20 000 $