Error Handling and Validation
Throw and Catch
throw stops the current path, and catch handles the error in one place.
Throw and Catch
throw.ts
function divide(total: number, parts: number): number {
if (parts === 0) {
throw new Error("parts must not be zero");
}
return total / parts;
}
const parts: number = ;
try {
const result: number = divide(20, parts);
console.log(`result=${result}`);
} catch (error) {
console.log("result=unavailable");
}
function divide(total: number, parts: number): number {
if (parts === 0) {
throw new Error("parts must not be zero");
}
return total / parts;
}
const parts: number = ;
try {
const result: number = divide(20, parts);
console.log(`result=${result}`);
} catch (error) {
console.log("result=unavailable");
}
function divide(total: number, parts: number): number {
if (parts === 0) {
throw new Error("parts must not be zero");
}
return total / parts;
}
const parts: number = ;
try {
const result: number = divide(20, parts);
console.log(`result=${result}`);
} catch (error) {
console.log("result=unavailable");
}
throw
`throw` raises an error, and a nearby `try`/`catch` can recover with fallback behavior.