Exception
- In Turkish
- İstisna
In short
An exception is an event that interrupts a program's normal flow when an error occurs, which code can catch and handle instead of letting the program crash.
What is an exception in programming?
An exception signals that something went wrong while the program was running, such as a missing file, a failed network request, or invalid input. When code throws (or raises) an exception, normal execution stops at that point. The program then looks for code that has declared it can handle the problem.
Exceptions travel up the call stack. If the function that threw the exception doesn't catch it, the function that called it gets a chance, then that function's caller, and so on. You handle exceptions by wrapping risky code in a try block and adding a catch block (called except in Python) that runs if an error occurs, plus an optional finally block that runs either way, which is useful for cleanup such as closing files. If nothing catches the exception, the program or request usually fails with an error message and a stack trace.
A fire alarm is a good analogy for an exception. When it goes off, everyone stops what they're doing and the people trained to deal with fires take over; if nobody responds, the whole building is evacuated. Exceptions let programs keep the main 'happy path' logic separate from the code that deals with problems.
Exceptions are often confused with errors in general. Syntax errors stop code from running at all, while exceptions happen at runtime and can be handled. Some languages, such as Go and Rust, prefer returning errors as ordinary values instead of throwing exceptions, which makes every possible failure visible in the code. Catching an exception and silently ignoring it is a common anti-pattern, because it hides bugs.
Key takeaways
- An exception interrupts normal execution when an error occurs at runtime.
- Code throws an exception, and a
try/catchblock can catch and handle it. - Uncaught exceptions move up the call stack and can crash the program.
- A
finallyblock runs whether or not an exception occurred, which suits cleanup work. - Only catch exceptions you can handle meaningfully; silently swallowing them hides bugs.
Example
function parseAge(input) {
const age = Number(input);
if (Number.isNaN(age)) {
throw new Error(`"${input}" is not a number`); // stop and signal a problem
}
return age;
}
try {
parseAge("abc");
} catch (error) {
console.error("Invalid input:", error.message); // handle the problem
} finally {
console.log("Validation finished"); // always runs
}Readers ask
What is the difference between an error and an exception?
The terms are often used interchangeably, and in many languages an exception is simply the object used to report a runtime error. Java also distinguishes Error, for serious problems an application shouldn't try to handle, such as running out of memory, from Exception, which code is expected to catch.
What is a stack trace?
A stack trace is the list of function calls that were active when an exception was thrown, printed with file names and line numbers. Reading it from the top shows where the problem happened and how the program got there.
How do I handle errors with async/await?
Wrap the await calls in a try/catch block. Inside an async function, a rejected promise behaves like a thrown exception, so the catch block receives the error.
See also
- FunctionProgramming Fundamentals, p. 21A function is a named, reusable block of code that performs a specific task, optionally taking inputs called parameters and returning a result.
- Async/AwaitProgramming Fundamentals, p. 4Async/await is a syntax for writing asynchronous code that reads like ordinary step-by-step code, pausing at each await until a promise or task finishes.
- PromiseProgramming Fundamentals, p. 46A promise is an object that represents the eventual result of an asynchronous operation, letting code react to success or failure once the work completes.
- CallbackProgramming Fundamentals, p. 7A callback is a function passed as an argument to another function, which then calls it later, for example when a task finishes or an event happens.
- ClassProgramming Fundamentals, p. 9A class is a blueprint in object-oriented programming that defines the data and behavior shared by a group of objects, which are created from it as instances.
- Stack TraceProgramming Fundamentals, p. 52A stack trace is the list of function calls in progress when an error happened, from the line that failed back to where the program started.
Spotted a mistake or something missing on this page?Suggest an edit