You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: 1-js/10-error-handling/1-try-catch/article.md
+71-71Lines changed: 71 additions & 71 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,47 +1,48 @@
1
-
# Error handling, "try..catch"
1
+
# Penanganan eror, "try..catch"
2
2
3
-
No matter how great we are at programming, sometimes our scripts have errors. They may occur because of our mistakes, an unexpected user input, an erroneous server response, and for a thousand other reasons.
4
3
5
-
Usually, a script "dies" (immediately stops) in case of an error, printing it to console.
4
+
Tidak peduli seberapa jagonya kita dalam pemograman, terkadang kodingan kita memiliki banyak eror. Mereka mungkin muncul dikarenakan kesalahan kita, input dari user yang tidak terduga, eror respon dari server, dan juga berbagai macam alasan lainnya.
6
5
7
-
But there's a syntax construct `try..catch` that allows us to "catch" errors so the script can, instead of dying, do something more reasonable.
6
+
Biasanya, sebuah kodingan/script "terhenti" (tiba-tiba berhenti) dikarenakan adanya eror, menampilkan erornya pada console.
8
7
9
-
## The "try..catch" syntax
8
+
Tapi terdapat sebuah sintaks `try..catch` yang memperbolehkan kita untuk "menangkap" hasil eror sehingga script bisa berjalan sesuai dengan arahan kita dibanding hanya berhenti.
10
9
11
-
The `try..catch` construct has two main blocks: `try`, and then `catch`:
10
+
## Sintaks "try..catch"
11
+
12
+
Sintaks `try..catch` membentuk dua bagian utama: pertama `try`, dan kemudian `catch`:
12
13
13
14
```js
14
15
try {
15
16
16
-
//code...
17
+
//kodingan disini
17
18
18
19
} catch (err) {
19
20
20
-
//error handling
21
+
//Penanganan jika eror
21
22
22
23
}
23
24
```
24
25
25
-
It works like this:
26
+
Mereka akan bekerja seperti ini:
26
27
27
-
1.First, the code in `try {...}`is executed.
28
-
2.If there were no errors, then`catch(err)`is ignored: the execution reaches the end of `try`and goes on, skipping`catch`.
29
-
3.If an error occurs, then the`try`execution is stopped, and control flows to the beginning of `catch(err)`. The`err`variable (we can use any name for it) will contain an error object with details about what happened.
28
+
1.Pertama, kodingan pada `try {...}`akan dijalankan.
29
+
2.Jika tidak terdapat eror, maka`catch(err)`akan dihiraukan: prosesnya akan mencapai ujung bagian `try`dan kemudian berlanjut, melewati bagian`catch`.
30
+
3.Jika terdapat eror, maka bagian`try`akan berhenti berjalan, dan alur prosesnya akan berlanjut di pada awal bagian `catch(err)`. Variabel`err`(yang mana kita bisa ganti dengan nama apapun) akan mengandung eror objek dengan keterangan eror didalamnya.
30
31
31
32

32
33
33
-
So, an error inside the`try {…}`block does not kill the script -- we have a chance to handle it in`catch`.
34
+
Jadi, sebuah eror didalam bagian`try {…}`tidak akan memberhentikan kodingan tersebut -- kita memiliki sebuah kesempatan untuk menanganinya pada bagian`catch`.
34
35
35
-
Let's look at some examples.
36
+
Mari kita lihat contoh lainnya.
36
37
37
-
-An errorless example: shows`alert``(1)` and `(2)`:
38
+
-Sebuah contoh tanpa eror: menampilkan`alert``(1)` and `(2)`:
38
39
39
40
```js run
40
41
try {
41
42
42
43
alert('Start of try runs'); // *!*(1) <--*/!*
43
44
44
-
// ...no errors here
45
+
// ...tidak ada eror disini
45
46
46
47
alert('End of try runs'); // *!*(2) <--*/!*
47
48
@@ -51,7 +52,7 @@ Let's look at some examples.
51
52
52
53
}
53
54
```
54
-
-An example with an error: shows `(1)` and `(3)`:
55
+
-Sebuah contoh dengan eror: shows `(1)` and `(3)`:
55
56
56
57
```js run
57
58
try {
@@ -72,10 +73,11 @@ Let's look at some examples.
72
73
```
73
74
74
75
75
-
````warn header="`try..catch` only works for runtime errors"
76
-
For `try..catch` to work, the code must be runnable. In other words, it should be valid JavaScript.
76
+
````warn header="`try..catch` hanya akan bekerja pada eror runtime"
77
+
Untuk `try..catch` agar bekerja, kodingan tersebut harus bisa dijalankan. Dengan artian lain, itu harus dalam bahasa javascript yang valid.
78
+
79
+
Mereka tidak akan bekerja jika kodingan tersebut secara sintaks salah, sebagai contoh jika mereka memiliki kurung kurawal yang tidak sama:
77
80
78
-
It won't work if the code is syntactically wrong, for instance it has unmatched curly braces:
79
81
80
82
```js run
81
83
try {
@@ -84,66 +86,66 @@ try {
84
86
alert("The engine can't understand this code, it's invalid");
85
87
}
86
88
```
89
+
Mesin Javascript pertama membaca kodingan tersebut, dan menjalankannya. eror yang terjadi pada saat proses pembacaan disebut sebagai eror "parse-time" dan tidak dapat dipulihkan (dari dalam kodingan tersebut). Itu dikarenakan mesin javascript tidak mengerti kodingan .
87
90
88
-
The JavaScript engine first reads the code, and then runs it. The errors that occur on the reading phase are called "parse-time" errors and are unrecoverable (from inside that code). That's because the engine can't understand the code.
89
-
90
-
So, `try..catch` can only handle errors that occur in valid code. Such errors are called "runtime errors" or, sometimes, "exceptions".
91
+
Jadi, `try..catch` hanya dapat menangani eror yang terjadi pada kodingan yang valid. eror demikian biasanya dinamakan sebagai "eror runtime" atau terkadang, "exceptions".
91
92
````
92
93
93
94
94
-
````warn header="`try..catch` works synchronously"
95
-
If an exception happens in "scheduled" code, like in `setTimeout`, then `try..catch` won't catch it:
95
+
````warn header="`try..catch` bekerja secara sinkronis"
96
+
Jika sebuah exception terjadi pada kodingan yang "terjadwal", seperti pada`setTimeout`, maka`try..catch` won't catch it:
96
97
97
98
```js run
98
99
try {
99
100
setTimeout(function() {
100
-
noSuchVariable; // script will die here
101
+
noSuchVariable; // kodingan akan berhenti disini
101
102
}, 1000);
102
103
} catch (e) {
103
104
alert( "won't work" );
104
105
}
105
106
```
106
107
107
-
That's because the function itself is executed later, when the engine has already left the `try..catch` construct.
108
+
Itu dikarenakan fungsi tersebut dijalankan nanti, ketika mesin javascript telah meninggalkan bagian pada `try..catch`.
108
109
109
-
To catch an exception inside a scheduled function, `try..catch` must be inside that function:
110
+
Untuk menangkap sebuah exception didalam sebuah fungsi yang terjadwal, `try..catch` harus terjadi didalam fungsi tersebut:
When an error occurs, JavaScript generates an object containing the details about it. The object is then passed as an argument to `catch`:
124
+
Ketika sebuah eror terjadi, Javascript menghasilkan sebuah ojek yang berisikan keterangan terkait eror tersebut. Objek itu kemudian dilewatkan sebagai sebuah argumen pada bagian `catch`:
124
125
125
126
```js
126
127
try {
127
128
// ...
128
-
} catch(err) { // <-- the "error object", could use another word instead of err
129
+
} catch(err) { // <-- "error object", bisa menggunakan kata lain selain err
129
130
// ...
130
131
}
131
132
```
132
133
133
-
For all built-in errors, the error object has two main properties:
134
+
Untuk semua eror bawaan, eror objek memiliki dua properti utama:
134
135
135
136
`name`
136
-
: Error name. For instance, for an undefined variable that's`"ReferenceError"`.
137
+
: Nama error. sebagai contoh, untuk variable yang belum terdefinisikan maka itu disebut `"ReferenceError"`.
137
138
138
139
`message`
139
-
:Textual message about error details.
140
+
: Pesan yang ada didalam eror tersebut.
140
141
141
-
There are other non-standard properties available in most environments. Oneof most widely used and supported is:
142
+
Terdapat properti non-standard lainnya pada kebanyakan
143
+
Ada properti non-standar lain yang tersedia di sebagian besar lingkungan. Salah satu yang paling banyak digunakan dan didukung ialah:
142
144
143
145
`stack`
144
-
:Current call stack: a string with information about the sequence of nested calls that led to the error. Usedfor debugging purposes.
146
+
: Call stack saat ini: string dengan informasi tentang urutan panggilan bertingkat yang menyebabkan kesalahan. Digunakan untuk tujuan debugging.
145
147
146
-
For instance:
148
+
Sebagai contoh:
147
149
148
150
```js run untrusted
149
151
try {
@@ -161,104 +163,102 @@ try {
161
163
}
162
164
```
163
165
164
-
## Optional"catch" binding
166
+
## Opsional"catch" binding
165
167
166
168
[recent browser=new]
167
169
168
-
If we don't need error details, `catch` may omit it:
170
+
Jika kita tidak butuh detail tentang eror, `catch` mungkin bisa menghilangkannya:
169
171
170
172
```js
171
173
try {
172
174
// ...
173
-
} catch { // <-- without (err)
175
+
} catch { // <-- tanpa (err)
174
176
// ...
175
177
}
176
178
```
177
179
178
-
## Using "try..catch"
180
+
## Menggunakan"try..catch"
179
181
180
-
Let's explore a real-life use case of`try..catch`.
182
+
Mari kita telusuri contoh penggunaan nyata dari `try..catch`.
181
183
182
-
As we already know, JavaScript supports the [JSON.parse(str)](mdn:js/JSON/parse) method to read JSON-encoded values.
184
+
Seperti yang telah kita ketahui, Javascript mendukung method [JSON.parse(str)](mdn:js/JSON/parse) yang membaca dari nilai JSON-encoded.
183
185
184
-
Usually it's used to decode data received over the network, from the server or another source.
186
+
Biasanya digunakan untuk memecahkan kode data yang diterima melalui jaringan, dari server atau sumber lain.
185
187
186
-
We receive it and call `JSON.parse` like this:
188
+
Kita menerimanya dan memanggil `JSON.parse` seperti ini:
187
189
188
190
```js run
189
-
let json = '{"name":"John", "age":30}'; // data from the server
191
+
let json = '{"name":"John", "age": 30}'; // data dari server
190
192
191
193
*!*
192
-
let user = JSON.parse(json); // convert the text representation to JS object
194
+
let user = JSON.parse(json); // mengonversi representasi teks ke objek JS
193
195
*/!*
194
196
195
-
// now user is an object with properties from the string
197
+
// sekarang pengguna adalah objek dengan properti dari string
196
198
alert( user.name ); // John
197
199
alert( user.age ); // 30
198
200
```
199
201
200
-
You can find more detailed information about JSON in the <info:json> chapter.
202
+
Kalian dapat menemukan informasi lebih detail tentang JSON di bab <info:json>.
201
203
202
-
**If `json` is malformed, `JSON.parse` generates an error, so the script "dies".**
204
+
**Jika format `json` salah,` JSON.parse` menghasilkan error, sehingga skrip "mati".**
203
205
204
-
Should we be satisfied with that? Of course not!
206
+
Cukupkah kita puas dengan itu? Tentu saja tidak!
205
207
206
-
This way, if something's wrong with the data, the visitor will never know that (unless they open the developer console). And people really don't like when something "just dies" without any error message.
208
+
Dengan cara ini, jika ada yang salah dengan datanya, pengunjung tidak akan pernah mengetahuinya (kecuali mereka membuka konsol pengembang). Dan orang biasanya tidak suka ketika sesuatu "berhenti begitu saja" tanpa ada pesan kesalahan.
207
209
208
-
Let's use`try..catch`to handle the error:
210
+
Mari gunakan `try..catch` untuk menangani kesalahan:
209
211
210
212
```js run
211
213
let json = "{ bad json }";
212
214
213
215
try {
214
216
215
217
*!*
216
-
let user = JSON.parse(json); // <-- when an error occurs...
218
+
let user = JSON.parse(json); // <-- ketika terjadi sebuah eror...
217
219
*/!*
218
-
alert( user.name ); // doesn't work
220
+
alert( user.name ); // tidak berjalan
219
221
220
222
} catch (e) {
221
223
*!*
222
-
// ...the execution jumps here
224
+
// ...proses eksekusinya akan lompat kesini
223
225
alert( "Our apologies, the data has errors, we'll try to request it one more time." );
224
226
alert( e.name );
225
227
alert( e.message );
226
228
*/!*
227
229
}
228
230
```
231
+
Di sini kita menggunakan blok `catch` hanya untuk menampilkan pesan, tetapi kita dapat melakukan lebih banyak lagi: mengirim permintaan jaringan baru, menyarankan alternatif kepada pengunjung, mengirim informasi tentang kesalahan ke fasilitas logging, .... Semuanya jauh lebih baik daripada sekedar mati.
229
232
230
-
Here we use the `catch` block only to show the message, but we can do much more: send a newnetwork request, suggest an alternative to the visitor, send information about the error to a logging facility, ... . All much better than just dying.
231
-
232
-
## Throwing our own errors
233
+
## Melontarkan eror kita sendiri
233
234
234
-
What if`json`is syntactically correct, but doesn't have a required `name` property?
235
+
Bagaimana jika `json` secara sintaksis benar, tetapi tidak memiliki properti` name` yang diperlukan?
235
236
236
-
Like this:
237
+
Seperti ini:
237
238
238
239
```js run
239
-
let json = '{ "age":30 }'; // incomplete data
240
+
let json = '{ "age":30 }'; // data tidak lengkap
240
241
241
242
try {
242
243
243
-
let user = JSON.parse(json); // <-- no errors
244
+
let user = JSON.parse(json); // <-- tidak ada eror
244
245
*!*
245
-
alert( user.name ); // no name!
246
+
alert( user.name ); // tidak ada nama!
246
247
*/!*
247
248
248
249
} catch (e) {
249
250
alert( "doesn't execute" );
250
251
}
251
252
```
253
+
Di sini `JSON.parse` berjalan normal, tetapi tidak adanya` nama` sebenarnya merupakan eror bagi kita.
252
254
253
-
Here `JSON.parse` runs normally, but the absence of `name` is actually an error for us.
255
+
Untuk menyatukan penanganan error, kita akan menggunakan operator `throw`.
254
256
255
-
To unify error handling, we'll use the `throw` operator.
0 commit comments