Skip to main content

Exception Handling

Ayesha
EditReport

Runtime errors can crash applications if they aren't caught. TypeScript uses modern try...catch...finally blocks to handle runtime errors gracefully.

Video Explanation​

1. Standard Error Handling Blocks​

try {
let numericalInput = 0;
if (numericalInput === 0) {
throw new Error("Cannot complete operations using zero boundaries.");
}
} catch (runtimeException: unknown) {
// Intercepts structural errors safely
if (runtimeException instanceof Error) {
console.error("Exception handled successfully: " + runtimeException.message);
}

} finally {
// Always executes, regardless of whether an error occurred
console.log("Cleaning up active system connections.");
}

2. Safe Catch Block Type Guarding​

In modern TypeScript configurations, caught errors are typed as unknown because JavaScript allows programs to throw any data type at runtime. You should always use instance validation guards before processing details:

try {
// Perform complex operations...
} catch (unverifiedError: unknown) {
if (unverifiedError instanceof Error) {
console.log(`Standard system exception detected: ${unverifiedError.message}`);
} else {
console.log("An anomalous, non-standard exception type was thrown.");
}
}

3. Developing Custom Domain Exceptions​

For granular error tracing, extend the base Error class to create custom exception types:

class DatabaseTimeoutException extends Error {
public timestampRecord: Date;

constructor(message: string) {
super(message);
this.name = "DatabaseTimeoutException";
this.timestampRecord = new Date();

// Corrects structural prototype alignment checks for custom classes
Object.setPrototypeOf(this, DatabaseTimeoutException.prototype);
}
}
Track Your Progress

Done with this topic? Mark it as complete to track your progress.

Was this page helpful?

💬

Discuss this page

Have a question or spot something confusing in "Exception Handling"? Ask below. Backed by GitHub Discussions—maintainers receive system notifications directly.