Wednesday, May 6, 2020

Exceptions

If your program encounters an unusual situation that does not allow to continue the normal flow of the code, it can throw an exception.

Example: the processArray function

let processArray = function (array) {
    // do type checking and throw an error object
    if (!Array.isArray(array)) {
        throw new Error("processArray: argument must be an array");
    }
    array.sort();
    array.reverse();
}
      
let array = [666, 1, 2, 222, 333, 555, 777];
    
try {
    processArray(array);
    console.log(array);
    processArray({}); // Error: processArray: argument must be an array
} catch (e) {
    console.error(e);
}  

the throw statement

In JavaScript you can throw any value, but it is customary to throw an object created by the Error function.
The throw statement interrupts execution of the function and transfers control to the enclosing catch or finally.

throw new Error('message');

The Error object properties

  • the Error object contains a name property that identifies the type of the exception and a descriptive message property.
  • the JavaScript implementation can produce these exception names: 'Error', 'EvalError', 'RangeError', 'SyntaxError', 'TypeError', 'URIError'.

What is the point of exception?

  • what's the difference between throwing an exception as opposed to returning undefined?
  • exceptions are intended to signal problems that the caller might not be able to handle.
  • for example, suppose that a function makes a HTTP request, gets a string form a server and then calls the JSON.parse function.
    If the server makes a serious mistake, JSON.parse will not be able to parse the string and will throw an exception.
    Then, the caller of JSON.parse can't fix the problem, it has to give up and let propagate the exception up the call stack. Until, some further up will deal with the problem.

The try/catch statement

The exception object is delivered to the catch clause of a try statement:

const troubleFunction = () => { 
    throw new Error('troubleFunction'); 
}

try {
    troubleFunction();
    console.log("this is skipped");
} catch (error) {
    // handle and/or log the exception
    console.log(error);
    console.log("this is executed");
}
// resume the normal flow of execution
console.log("this is executed also");

Handling exceptions

  • in the catch clause, you want to log the error
  • usually you don't want to analyze the type of the errors, you don't want the type of the exception to drive the control flow.

The try/finally statement

try {
    // open file
} finally {
    // close file
}

The finally clause

  • if is always executed, whether the try block was successful or whether an exception happened.
  • it is intended to release resources safely
  • Note: never use the return statement in this clause, as they do no interact well

No comments:

Post a Comment