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}
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}
1try {
2 alert( 'try' );
3 if (confirm('Make an error?')) BAD_CODE();
4} catch (e) {
5 alert( 'catch' );
6} finally {
7 alert( 'finally' );
8}
1let json = '{ "age": 30 }'; // incomplete data
2
3try {
4
5 let user = JSON.parse(json); // <-- no errors
6 alert( user.name ); // no name!
7
8} catch (e) {
9 alert( "doesn't execute" );
10}
1try {
2
3 alert('Start of try runs'); // (1) <--
4
5 lalala; // error, variable is not defined!
6
7 alert('End of try (never reached)'); // (2)
8
9} catch(err) {
10
11 alert(`Error has occurred!`); // (3) <--
12
13}