Exception
In one line
An exception is an error that occurs during program execution and can be caught and handled with try/catch.
In simple words
An exception is an error that happens while your program is running — like dividing by zero, accessing a null reference, or failing to open a file. Unlike syntax errors (caught before running), exceptions occur during execution and can be caught and handled gracefully.
The try/catch mechanism lets you wrap risky code: the try block runs the code, and if an exception occurs, execution jumps to the catch block where you can handle the error — log it, show a user-friendly message, or recover.
Without exception handling, an uncaught exception crashes the program. With it, you can anticipate problems and handle them gracefully. Common exceptions include TypeError, ReferenceError, RangeError in JavaScript, and ValueError, TypeError, KeyError in Python.
Example
try {
const data = JSON.parse("invalid json");
console.log(data);
} catch (error) {
console.log("Failed to parse JSON:", error.message);
}
// Output: Failed to parse JSON: Unexpected token...
// Program continues running instead of crashingJSON.parse throws an exception on invalid input. The try/catch catches it and prints a friendly message instead of crashing.
Related terms
Related Resources
Related Lessons
- Errors
Learn about errors and exceptions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.