Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
The difference becomes obvious when we look at the code inside a function.
ความแตกต่างจะเห็นชัดเมื่อดูโค้ดที่อยู่ภายในฟังก์ชัน

The behavior is different if there's a "jump out" of `try...catch`.
สองแบบนี้ทำงานต่างกันเมื่อมีการ "กระโดดออก" จาก `try...catch`

For instance, when there's a `return` inside `try...catch`. The `finally` clause works in case of *any* exit from `try...catch`, even via the `return` statement: right after `try...catch` is done, but before the calling code gets the control.
ยกตัวอย่างเช่น เมื่อมี `return` อยู่ใน `try...catch` บล็อก `finally` จะทำงานเสมอไม่ว่าจะออกจาก `try...catch` ด้วยวิธีไหน รวมถึง `return` ด้วย โดยจะรันหลังจาก `try...catch` ทำงานเสร็จ แต่ก่อนที่โค้ดที่เรียกฟังก์ชันจะได้รับค่ากลับ

```js run
function f() {
Expand All @@ -21,7 +21,7 @@ function f() {
f(); // cleanup!
```

...Or when there's a `throw`, like here:
...หรือเมื่อมี `throw` แบบนี้:

```js run
function f() {
Expand All @@ -44,4 +44,4 @@ function f() {
f(); // cleanup!
```

It's `finally` that guarantees the cleanup here. If we just put the code at the end of `f`, it wouldn't run in these situations.
`finally` นี่แหละที่รับประกันว่าจะเคลียร์งานได้เสมอ ถ้าเราแค่เขียนโค้ดไว้ต่อท้ายฟังก์ชัน `f` เฉยๆ โค้ดส่วนนั้นจะไม่ทำงานในสถานการณ์เหล่านี้
24 changes: 12 additions & 12 deletions 1-js/10-error-handling/1-try-catch/1-finally-or-code-after/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,37 +2,37 @@ importance: 5

---

# Finally or just the code?
# ใช้ `finally` หรือเขียนโค้ดต่อท้ายดี?

Compare the two code fragments.
ลองเปรียบเทียบโค้ดสองแบบนี้

1. The first one uses `finally` to execute the code after `try...catch`:
1. แบบแรกใช้ `finally` รันโค้ดหลัง `try...catch`:

```js
try {
work work
ทำงาน ทำงาน
} catch (err) {
handle errors
จัดการ error
} finally {
*!*
cleanup the working space
เคลียร์งาน
*/!*
}
```
2. The second fragment puts the cleaning right after `try...catch`:
2. แบบที่สองเขียนโค้ดเคลียร์งานไว้ต่อท้าย `try...catch` เลย:

```js
try {
work work
ทำงาน ทำงาน
} catch (err) {
handle errors
จัดการ error
}

*!*
cleanup the working space
เคลียร์งาน
*/!*
```

We definitely need the cleanup after the work, doesn't matter if there was an error or not.
เราต้องเคลียร์งานหลังทำงานเสร็จแน่นอน ไม่ว่าจะเกิด error หรือไม่ก็ตาม

Is there an advantage here in using `finally` or both code fragments are equal? If there is such an advantage, then give an example when it matters.
ถ้าอย่างนั้น ใช้ `finally` มีข้อได้เปรียบกว่าไหม หรือสองแบบนี้ให้ผลเหมือนกัน? ถ้ามีข้อได้เปรียบ ลองยกตัวอย่างกรณีที่มันสำคัญ
Loading