Skip to content

Error Handling

Error handling: try/except instead of try/catch

Section titled “Error handling: try/except instead of try/catch”

Python’s error handling maps directly onto TypeScript’s try/catch/finally — with one powerful addition: an else clause that runs only when NO exception was raised. The keywords are try/except/else/finally, and you raise exceptions instead of throw.

TypeScript
// TypeScript
function divide(a: number, b: number): number {
if (b === 0) throw new Error("Cannot divide by zero");
return a / b;
}
try {
const result = divide(10, 2);
console.log(`Result: ${result}`);
} catch (err) {
if (err instanceof Error) {
console.error(`Error: ${err.message}`);
}
} finally {
console.log("Always runs");
}
Python
# Python
def divide(a: float, b: float) -> float:
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
try:
result = divide(10, 2)
print(f"Result: {result}")
except ValueError as e:
print(f"Error: {e}")
finally:
print("Always runs")

Key differences:

  • except instead of catch.
  • raise instead of throw.
  • You catch a specific exception type directly (e.g. except ValueError), not a generic value.
  • The as e syntax binds the exception object.
TypeScript
// TypeScript
try {
const data = JSON.parse("{ bad json }");
const num = parseInt("abc", 10);
if (isNaN(num)) throw new RangeError("NaN");
} catch (err) {
if (err instanceof SyntaxError) {
console.error("JSON error:", err.message);
} else if (err instanceof RangeError) {
console.error("Range error:", err.message);
} else {
throw err; // re-raise unknown errors
}
}
Python
# Python — multiple except clauses
import json
try:
data = json.loads("{ bad json }")
value = int("abc")
except json.JSONDecodeError as e:
print(f"JSON error: {e}")
except ValueError as e:
print(f"Value error: {e}")
except Exception as e:
raise # re-raise any other exception
# You can also catch multiple types in one clause:
# except (ValueError, TypeError) as e:
# print(f"Either error: {e}")
TypeScript
// TypeScript
class AppError extends Error {
constructor(
message: string,
public readonly code: number
) {
super(message);
this.name = "AppError";
}
}
try {
throw new AppError("Not found", 404);
} catch (err) {
if (err instanceof AppError) {
console.log(`[${err.code}] ${err.message}`);
}
}
Python
# Python
class AppError(Exception):
def __init__(self, message: str, code: int) -> None:
super().__init__(message)
self.code = code
try:
raise AppError("Not found", 404)
except AppError as e:
print(f"[{e.code}] {e}")
def divide(a: float, b: float) -> float:
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
# Successful case
try:
result = divide(10, 2)
print(f"10 / 2 = {result}")
except ValueError as e:
print(f"Error: {e}")
else:
print("No error occurred (else clause)")
finally:
print("Always runs")
print()
# Error case
try:
result = divide(10, 0)
except ValueError as e:
print(f"Caught: {e}")
else:
print("This will NOT print")
finally:
print("Finally again")
What is the Python equivalent of JavaScript's `throw new Error("msg")`?
When does the `else` clause of a `try` block run in Python?
How do you catch multiple exception types in a single `except` clause?
When does the `finally` block run?