Bài viết hướng dẫn sử dụng JavaScript này cung cấp cho bạn một cái nhìn chi tiết hơn về câu lệnh Try-Catch
của ngôn ngữ lập trình web JavaScript thông qua các giải thích và ví dụ cụ thể
- Demo
- Phóng to
- Tải lại
- Cửa sổ mới
Miễn phí web hosting 1 năm đầu tại iPage
Nếu bạn vẫn còn đang tìm kiếm một nhà cung cấp hosting đáng tin cậy, tại sao không dành chút thời gian để thử với iPage, chỉ với không quá 40.000 VNĐ/tháng, nhưng bạn sẽ được khuyến mãi kèm với quà tặng trị giá trên 10.000.0000 VNĐ nếu thanh toán cho 24 tháng ~ 900.000 VNĐ?
Có trên 1 triệu khách hàng hiện tại của iPage đã & đang hài lòng với dịch vụ, tuyệt đối chắc chắn bạn cũng sẽ hài lòng giống họ! Quan trọng hơn, khi đăng ký sử dụng web hosting tại iPage thông qua sự giới thiệu của chúng tôi, bạn sẽ được hoàn trả lại toàn bộ số tiền bạn đã sử dụng để mua web hosting tại iPage. Wow, thật tuyệt vời! Bạn không phải tốn bất kì chi phí nào mà vẫn có thể sử dụng miễn phí web hosting chất lượng cao tại iPage trong 12 tháng đầu tiên. Chỉ cần nói chúng tôi biết tài khoản của bạn sau khi đăng ký.
Nếu muốn tìm hiểu thêm về ưu / nhược điểm của iPage, bạn hãy đọc đánh giá của ChọnHostViệt.com nhé!
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.
- Lượt gửi (0)
- Mới
Tạo video doanh nghiệp của bạn bằng AI chỉ với giọng nói hoặc văn bản
chatGPTaz.com
Nói chuyện với ChatGPT bằng ngôn ngữ mẹ đẻ của bạn
Ứng dụng AI Video
Ứng dụng video AI MIỄN PHÍ đầu tiên của bạn
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 trực tuyến
Đổi mặt Video, Ảnh & GIF ngay lập tức với Công cụ AI mạnh mẽ - Faceswap AI Trực tuyến MIỄN PHÍ
Faceswap AI trực tuyến
Đổi mặt Video, Ảnh & GIF ngay lập tức với Công cụ AI mạnh mẽ - Faceswap AI Trực tuyến MIỄN PHÍ
Temu tặng $500 cho người dùng mới
Claim Free Temu $500 Credit via Affiliate & Influencer Program
Tín dụng quảng cáo TikTok miễn phí
Làm chủ quảng cáo TikTok cho hoạt động tiếp thị doanh nghiệp của bạn
Dall-E-OpenAI.com
Tự động tạo ra hình ảnh sáng tạo với AI
chatGPT4.win
Nói chuyện với ChatGPT bằng ngôn ngữ mẹ đẻ của bạn
Sản phẩm AI đầu tiên của Elon Musk - Grok/UN.com
Nói chuyện với Grok AI Chatbot bằng ngôn ngữ của bạn
Công cụ.win
Mở trung tâm công cụ miễn phí để mọi người sử dụng với hàng trăm công cụ
GateIO.gomymobi.com
Airdrop miễn phí để nhận, chia sẻ lên đến 150.000 đô la cho mỗi dự án
iPhoneKer.com
Tiết kiệm tới 630$ khi mua iPhone 16 mới
Mua Robot Tesla Optimus
Đặt mua Tesla Bot: Robot Optimus Gen 2 ngay hôm nay với giá dưới 20.000 đô la