1try {
2 // Try to run this code
3}
4catch(err) {
5 // if any error, Code throws the error
6}
7finally {
8 // Always run this code regardless of error or not
9 //this block is optional
10}
1try {
2 nonExistentFunction();
3} catch (error) {
4 console.error(error);
5 // expected output: ReferenceError: nonExistentFunction is not defined
6 // Note - error messages will vary depending on browser
7}
1var someNumber = 1;
2try {
3 someNumber.replace("-",""); //You can't replace a int
4} catch(err) {
5 console.log(err);
6}
1"The try...catch statement marks a block of statements to try and specifies"
2"a response should an exception be thrown."
3
4try {
5 nonExistentFunction();
6} catch (error) {
7 console.error(error);
8 // expected output: ReferenceError: nonExistentFunction is not defined
9 // Note - error messages will vary depending on browser
10}
11
1try { // Try to run this code
2 alert( 'try' );
3 if (confirm('Make an error?')) BAD_CODE();
4} catch (e) { // Code throws error
5 alert( 'catch' );
6} finally { // Always run this code regardless of error or not
7 alert( 'finally' );
8}
1<html>
2<head>Exception Handling</head>
3<body>
4<script>
5try {
6 throw new Error('This is the throw keyword'); //user-defined throw statement.
7}
8catch (e) {
9 document.write(e.message); // This will generate an error message
10}
11</script>
12</body>
13</html>