Make writing a habit together! This is the 14th day of my participation in the “Gold Digging Day New Plan · April More Text Challenge”. Click here for more details.


This article was first published in: My Zhihu

As anyone who has studied try/catch/finally knows, this is a relatively simple error-handling mechanism. However, for beginners, some details may be difficult to understand. In this article, you can understand try/catch/finally from the beginning.

If you think you understand, then please take a look at this problem first.

const whoami = () = > {
  try {
    try {
      return ' ';
    } catch(_) {
      return ' ';
    } finally {
      return ' ';
    }
    throw ' ';
  } catch (_) {
    return ' '; } } whoami(); What will be the return value of the function?Copy the code

1. Why?

Try /catch/finally is used to handle possible errors in your code. It is needed because when a JavaScritp execution error occurs, the execution of the following program will stop, and the exception will cause the program to crash. So using try/catch/finally to handle errors is important for maintenance of future projects. Such as:

const PI = 3.14;
alertt('Hello! ');
console.log(PI);
// ReferenceError: alertt is not defined
Copy the code

Alertt is clearly misspelled, so subsequent programs will not execute. So use try/catch/finally to handle exceptions

const PI = 3.14;
try {
  alertt('Hello! ');
} catch(err) {
  console.log(err.message);
} finally {
  console.log(PI);
}
/*
alertt is not defined
3.14
*/
Copy the code

2. How does it work?

  • tryStatement defines the code that is executed to test for errors. If no exception is thrown inside the try, the catch is skipped.
  • catchStatement definition whentryWhen an error occurs in a statement, the error is caught and processed. Only when thetryAn error is thrown before it is executed.
  • finallyThe statement executes regardless of whether an exception precedes it. |

When used, the try statement is required; Catch (err) parameters are required; Both Catch and finally are optional. That is, the following three forms

  • try... catch
  • try... finally
  • try... catch.. finally

Throw and Error objects

3.1 throw

We can use throw statements to generate errors and customize the exceptions thrown

throw 'error! ';
throw false;
Copy the code

For example, the following statement restricts the form of input

var input = 1314;
try {
  if(input == ' ') throw "Please enter!";
  if(isNaN(input)) throw "Please enter a number!";
  if(input <= 0) throw "Please enter a number greater than 0!"
} catch(err) {
  alert(err);
}
Copy the code

3.2 throw and try/catch/finally

We call the outer try block “outer” and the inner block “inner”. The following

The outer block "/ /"
try {
  / / "inner piece"
  try {
    throw "error";
  } catch(err) {
    console.log('inner:' + err);
    throw "error"; }}catch(err) {
  console.log("outer:" + err);
}
Inner :error finally outer:error */
Copy the code

The final output indicates that a thrown exception will only be caught by the nearest catch. Furthermore, exceptions thrown by the “inner” layer can also be caught by the “outer” layer.

3.3 the Error object

Error has name and message attributes

try {
    adddlert("Welcome");
}
catch(err) {
  console.log(err.name);
  console.log(err.message);
}
ReferenceError adddlert is not defined */
Copy the code

3.4 Throw and Error objects

throw new Error("error!")
Copy the code

4. Return and try/catch/finally

We all know that in a function, once a return appears, the following statement is not executed. What happens if there is a return ina try/catch/finally? A statement in finally is always executed, whether or not an exception occurs or a return precedes a try/catch

try {
  return "hello";
} finally {
  console.log("finally");
}
/* Finally */
Copy the code

If a return occurs early ina try/catch/finally, the rest of the block is not executed

const f = () = > {
  try {
    return "hello";
    console.log("try");
  } finally {
    return "hello";
    console.log("finally");
  }
}
f();
/ / no output
Copy the code

If a return is written to a function finally, the return value (or exception) of the function (the entire try/catch/finally) will be the value returned from the function finally, even if a retrun occurs in the previous try/catch

const func = () = > {
  try {
    try {
      throw new Error("ERROR!");
    } catch(err) {
      console.log(err.message);
      throw new Error("error from inner")}finally {
      return "finally"; }}catch(err) {
   console.log(err.message); // No exception caught, no output here}}; func();/* output ERROR! * /
Copy the code

If you comment out the return “finally” above, error from inner will be printed. This warns us not to write a return in finally, or else it will overwrite the value of the function that was previously returned or even the error that was thrown

Now let’s go back to the first question

Refer to the link

  • try… catch
  • JavaScript try/catch/finally statement