Exception
An exception is an error that occurs while a program is running. If it is not handled, it stops the program; code can 'catch' exceptions to recover gracefully.
General Programming
Common exceptions include dividing by zero, accessing a missing file, or using an index that is out of range.
Most languages provide a try/catch (or try/except) structure so the program can respond to an error instead of crashing.
Syntax
try { risky() } catch (error) { handle(error) }Examples
Python
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")Output:
Cannot divide by zeroJavaScript
try {
JSON.parse("not json");
} catch (err) {
console.log("Caught:", err.name);
}Output:
Caught: SyntaxError