Throw ... Try ... Catch javascript

Throw ... Try ... Catch javascript
0.0 0

#1

Hi, I can’t catch the sense of this. Please, can you explain this to me like to a child please?


#2

Some things are designed to break if things go wrong. A try-catch block enables you to limit (catch) that breakage from ruining the whole program.

It’s especially useful if you don’t know in advance what will be executed. For example, imagine a smart calculator app, where the user can input any mathematical expression. It’s easier to just try to evaluate it instead of checking all possibilities of it going wrong (division by zero, negative logarithms and so on). The pseudocode could look like this:

var input = document.querySelector("#input").value;
try (eval(input)) {
  console.log("The expression is valid.");
} catch (exception) {
  alert("The expression is invalid, fix the input! Error was: " + exception);
}

#3

The try / catch block is a pattern for catching runtime errors and gives you the programmer a chance to deal with it if it occurs.

try {
   // do something here, say open a database
   // write a record to database
   // close database 
} catch (Exception e) {
   // something went wrong in the try { } block above
   // do something else instead if we know how to deal with this specific error/situation
   if (e.somekindoferror) {
          // do alternate action
   } 
   // if this error is totally something unexpected and we don't know what to do with it,
   // just re-raise the error again, and let the operating system deal with it. 
   throw;     // at this point, the program would probably end with the specific error message
}





#4

thank you guys :slight_smile: