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}
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
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}