JavaScript deneyin...yakalayın...sonunda
Örnek
Bu örnekte try bloğunda yazım hatası var . Uyarı yanlış yazılmış.
Catch bloğu hatayı yakalar ve onu işlemek için kodu yürütür:
<p id="demo"></p>
<script>
try {
adddlert("Welcome guest!");
}
catch(err) {
document.getElementById("demo").innerHTML = err.message;
}
</script>
Aşağıda daha fazla örnek.
Tanım ve Kullanım
Bir hata oluştuğunda JavaScript duracak ve bir hata mesajı oluşturacaktır.
Not
Bunun teknik terimi şudur: JavaScript bir istisna atar .
JavaScript, iki özelliğe sahip bir Error nesnesi oluşturur: name ve message .
İfadeler , try...catch...finally
JavaScript'i durdurmadan hataları işler.
İfade try
, çalıştırılacak (denemek) kod bloğunu tanımlar.
İfade catch
, herhangi bir hatayı işlemek için bir kod bloğu tanımlar.
İfade finally
, sonuçtan bağımsız olarak çalıştırılacak bir kod bloğu tanımlar.
İfade throw
, özel bir hatayı tanımlar.
Her ikisi catch
de finally
isteğe bağlıdır, ancak bunlardan birini kullanmanız gerekir.
Not
Fırlatmayı dene ve yakala ile kullanmak , program akışını kontrol etmenize ve özel hata mesajları oluşturmanıza olanak tanır.
Ayrıca bakınız:
Sözdizimi
try {
tryCode - Code block to run
}
catch(err) {
catchCode -
Code block to handle errors
}
finally {
finallyCode - Code block to be executed regardless of the try result
}
parametreler
Parameter | Description |
tryCode | Required. Code block to be tested while executing. |
err | A local reference to the error object. |
catchCode | Optional. Code block to execute if an error occurs. |
finallyCode | Optional. Code block to execute regardless of the try result |
Daha fazla örnek
Bu örnek girdiyi inceler.
Değer yanlışsa, bir istisna (err) atılır:
<p>Please input a number between
5 and 10:</p>
<input id="demo" type="text">
<button type="button"
onclick="myFunction()">Test Input</button>
<p id="message"></p>
<script>
function myFunction() {
const message =
document.getElementById("message");
message.innerHTML = "";
let x =
document.getElementById("demo").value;
try {
if(x == "") throw "is Empty";
if(isNaN(x)) throw "not a number";
if(x > 10) throw "too high";
if(x < 5) throw "too low";
}
catch(err) {
message.innerHTML =
"Input " + err;
}
}
</script>
nihayet ifadesi , deneme sonucundan bağımsız olarak kodu yürütür:
function myFunction()
const message =
document.getElementById("message");
message.innerHTML = "";
let x =
document.getElementById("demo").value;
try {
if(x == "") throw "Empty";
if(isNaN(x))
throw "Not a number";
if(x >
10) throw "Too high";
if(x <
5) throw "Too low";
}
catch(err)
{
message.innerHTML = "Error: " +
err + ".";
}
finally {
document.getElementById("demo").value = "";
}
}
Tarayıcı Desteği
try...catch
bir ECMAScript3 (ES3) özelliğidir.
ES3 (JavaScript 1999), tüm tarayıcılarda tam olarak desteklenir:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes | Yes |