Try Catch Finally Flashcards
What are the component methods of a try catch block?
Try, catch, finally
What is a try catch block?
The try…catch statement is comprised of a try block and either a catch block, a finally block, or both. The code in the try block is executed first, and if it throws an exception, the code in the catch block will be executed. The code in the finally block will always be executed before control flow exits the entire construct.
What is the format of a try catch block?
try {
console.log(test);
} catch (e) {
console.error(‘Error Message:’, e.message); //Error Message: test is not defined
} finally {
console.error(‘Finally Message’); //Finally Message
}
What is the purpose of the finally block?
Statements that are executed before control flow exits the try…catch…finally construct. These statements execute regardless of whether an exception was thrown or caught.
What are different forms of the try catch block?
try…catch
try…finally
try…catch…finally
What is catch binding?
When an exception is thrown in the try block, exceptionVar (i.e., the e in catch (e)) holds the exception value. You can use this binding to get information about the exception that was thrown. This binding is only available in the catch block’s scope.
What is the syntax for catch binding?
try {
throw new TypeError(“oops”);
} catch ({ name, message }) {
console.log(name); // “TypeError”
console.log(message); // “oops”
}
Uses destructuring to extract properties from error object.
What is the throw statement used for?
The throw statement throws a user-defined exception. Execution of the current function will stop (the statements after throw won’t be executed), and control will be passed to the first catch block in the call stack. If no catch block exists among caller functions, the program will terminate.
JavaScript has many built-in constructors for standard errors, what are they?
InternalError
RangeError
ReferenceError
SyntaxError
TypeError
What is the syntax for a thrown error?
throw errorVar;
throw new Error(“Required”);
throw new TypeError(“Can only add numbers”);
How does Automatic semicolon insertion affect thrown errors?
The syntax forbids line terminators between the throw keyword and the expression to be thrown.
Illegal:
throw
new Error();
The code above is transformed by automatic semicolon insertion (ASI) into:
throw;
new Error();
This is invalid code, because unlike return, throw must be followed by an expression.
Legal:
throw (
new Error()
);
What is a typical try catch use case?
try {
const data = await readFilePromise(“foo.txt”);
console.log(data);
} catch (err) {
console.error(err);
}
What is the syntax for a thrown error?
let json = ‘{ “age”: 30 }’; // incomplete data
try {
let user = JSON.parse(json); // <– no errors
if (!user.name) {
throw new SyntaxError(“Incomplete data: no name”); // (*)
}
alert( user.name );
} catch (err) {
alert( “JSON Error: “ + err.message ); // JSON Error: Incomplete data: no name
}