Organizing programs
JavaScript Exceptions
When the code runs into an unexpected problem, the JavaScript idiomatic way to handle this situation is through exceptions
When JavaScript hits a problem at runtime, the usual response is an exception: stop the normal flow and jump to a handler.
Creating exceptions
Use throw to raise one:
throw value
value can be a string, number, object, or an Error instance. As soon as throw runs, code after it in that path does not execute.
Handling exceptions
Wrap risky code in try/catch:
try {
//lines of code
} catch (e) {
}
e is the thrown value. You can add multiple catch blocks in some environments, or branch on e.name inside one handler.
finally
finally runs whether or not an exception happened:
try {
//lines of code
} catch (e) {
} finally {
}
Use finally to release resources you opened in try, such as closing a connection or clearing a flag.
You can omit catch and use try/finally when you only need cleanup:
try {
//lines of code
} finally {
}
Nested try blocks
try blocks can nest. An exception bubbles to the nearest matching catch:
try {
//lines of code
try {
//other lines of code
} finally {
//other lines of code
}
} catch (e) {
}
If the inner try has no catch, the outer catch handles the error.
Try this pattern with a function that throws when input is invalid. Log in catch, then confirm finally still runs.
Throw new Error('message') rather than a bare string when you want a useful stack trace in the console.
You can rethrow after logging if a lower layer should not swallow the failure: catch (e) { console.error(e); throw e }.
Libraries often wrap unknown thrown values with Error so callers always receive something with a stack. That keeps logs consistent across browsers.
Try this pattern with a function that throws when input is invalid. Log in catch, then confirm finally still runs.
Lesson completed