Javascript Tutorials — Error Capture (Try-Catch)
We continue our JavaScript classes with a try-catch structure, when the form information entered by the user is not in the desired format or type, we can catch the error and generate the appropriate warning messages or error messages with throw or notify the user from the system.
In our first application, the function named message is not defined and the error message is read from the system.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | <!DOCTYPE html> <html> <head> <title>https://opensourceprojects.org</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script> var uyari=""; function kontrol() { try { mesaj("welcome to opensourceprojects.org"); } catch(err) { uyari="create error in page"; uyari+="error: " + err.message + "n"; uyari+="please try again later.n"; alert(uyari); } } </script> </head> <body> <input type="button" value="hi" onclick="kontrol()" /> </body> </html> |
Check live version; http://jsfiddle.net/
In our second application entering a number in the text box, the number entered must be between 5-10 if entered outside this range, we will generate an error and give it to the user as a message..
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | <!DOCTYPE html> <html> <head> <title>https://opensourceprojects.org</title> <script> function kontrol() { var y=document.getElementById("hata"); y.innerHTML=""; try { var x=document.getElementById("sayi").value; if(x=="") throw "Boş"; if(isNaN(x)) throw "Sayı Değil"; if(x>10) throw "Büyük sayı"; if(x<5) throw "Küçük Sayı"; } catch(err) { y.innerHTML="Hata: " + err + "."; } } </script </head> <body> <p>5-10 arasında bir sayı girin</p> <input id="sayi" type="text"> <button type="button" onclick="kontrol()">Sayıyı Kontrol Et</button> <p id="hata"></p> </body> </html> |
check live version; http://jsfiddle.net/