Exception
Исключение
An exception is a signal that interrupts normal execution, often because an operation could not finish. Code can catch that signal and decide what to do next.
What an exception does
A function normally gives control back to its caller by returning a value or reaching the end of its body. An exception is another way out: the function stops before completing its normal work, and execution looks for code that knows how to respond. For example, a parser might throw an exception when given text that is not valid JSON. The parser knows what went wrong, but the caller knows whether to ask for new input, skip a record, or stop a job.
How exceptions travel
Put the operation you want to guard in a try block. If it throws, the remaining statements in that block are skipped. The runtime looks for a matching handler (catch in JavaScript, except in Python). If none is available in the current call, the exception propagates to its caller. Leaving those calls is called stack unwinding. An uncaught exception can fail a request, end a task, or terminate the program, depending on the runtime and its top-level handlers.
A finally block serves a different purpose: it runs when control leaves the try/catch construct, whether the code succeeds, returns early, or lets an exception propagate. Use it for cleanup, not as a substitute for a handler. Avoid returning from finally: in languages such as JavaScript, this can override a pending return or suppress an exception.
Example: parsing a setting
function parseSettings(text) {
try {
return JSON.parse(text);
} catch (error) {
if (!(error instanceof SyntaxError)) throw error;
return { theme: "light" };
}
}
This function deliberately falls back to a default for malformed JSON. It rethrows anything other than a SyntaxError instead of treating every failure as bad input. The example checks JSON syntax only: valid JSON can still have the wrong shape, so an application that requires a theme field needs a separate validation step.
Choosing where to handle a failure
Catch exceptions where you can take a useful action. A command-line entry point might turn a file error into a message and a nonzero exit code. A lower-level function might let the same exception propagate because it cannot decide what recovery means. For routine outcomes that callers are expected to branch on, such as a search with no matches, an empty collection or a result type may fit the API better.
In interviews
You may be asked to trace a nested try/catch/finally or explain why a handler missed an asynchronous error. In JavaScript, wrapping a call that returns a promise in try does not catch a later rejection on its own. If you await the promise inside the try, its rejection is thrown at the await and can be caught there.