? L? try istruzione consente di testare un blocco di codice per gli errori. ? L? catch istruzione ti consente di gestire l?errore. ?L? throw istruzione ti consente di creare errori personalizzati. ?L? finally istruzione ti consente di eseguire il codice, dopo aver provato e catturato, indipendentemente dal risultato. ?Gli errori accadranno! ?Quando si esegue il codice JavaScript, possono verificarsi errori diversi. ?Gli errori possono essere errori di codifica commessi dal programmatore, errori dovuti a input errati e altre cose imprevedibili. ?Esempio ?In questo esempio abbiamo scritto alert come adddlert per generare deliberatamente un errore: https://www.w3schools.com/js/tryit.asp?filename=tryjs_try_catch <!DOCTYPE html> <html> <body> <p id="demo"></p> <script> try { adddlert("Welcome guest!"); } catch(err) { document.getElementById("demo").innerHTML = err.message; } </script> </body> </html> ? L? throw istruzione ti consente di creare un errore personalizzato. ? Tecnicamente puoi lanciare un?eccezione (genera un errore) . ? L?eccezione pu? essere un JavaScript String, un Number, un Booleano un Object: https://www.w3schools.com/js/tryit.asp?filename=tryjs_throw_error <!DOCTYPE html> <html> <body> <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="p01"></p> <script> function myFunction() { var message, x; message = document.getElementById("p01"); message.innerHTML = ""; x = document.getElementById("demo").value; try { if(x == "") throw "empty"; if(isNaN(x)) throw "not a number"; x = Number(x); if(x < 5) throw "too low"; if(x > 10) throw "too high"; } catch(err) { message.innerHTML = "Input is " + err; } } </script> </body> </html> ?La dichiarazione finale ?L? finally istruzione ti consente di eseguire il codice, dopo aver provato e catturato, indipendentemente dal risultato: ? Sintassi ? try { ? Block of code to try ? } ? catch(err) { ? Block of code to handle errors ? } ? finally { ? Block of code to be executed regardless of the try / catch result ? } https://www.w3schools.com/js/tryit.asp?filename=tryjs_finally_error <!DOCTYPE html> <html> <body> <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="p01"></p> <script> function myFunction() { var message, x; message = document.getElementById("p01"); message.innerHTML = ""; x = document.getElementById("demo").value; try { if(x == "") throw "is empty"; if(isNaN(x)) throw "is not a number"; x = Number(x); if(x > 10) throw "is too high"; if(x < 5) throw "is too low"; } catch(err) { message.innerHTML = "Input " + err; } finally { document.getElementById("demo").value = ""; } } </script> </body> </html> |