← Back to Articles

Error handling

Comparison between JavaScript and Python

The information comes from the Udemy course "Become an AI Engineer: Python for JavaScript Developers" by Vilva Athiban

Feature JavaScript Python
error catching try / catch / finally
function divFn() {
  return "hello";
}

try {
  divFn();
} catch (error) {
  console.log(error);
} finally {
  console.log("I am done");
}
try / except / finally
try:
    div_fn()
except Exception as error: # `except`
    print(error)
finally:
    print("I am done")
Throwing errors throw
function risky() {
  throw new Error("this is a type error");
}

try {
  risky();
} catch (error) {
  console.log(error.message);   
  // "this is a type error"
}
raise
def risky():
    raise TypeError("this is a type error")   
    # can't just `raise "..."`

try:
    risky()
except Exception as error:
    print(error)  # "this is a type error"
specific error types
try {
  risky();
} catch (error) {
  if (error instanceof TypeError) {
    console.log("this is a type error");
  } else {
    console.log("some other error");
  }
}

// --- Custom error types ---
class CustomError extends Error {}

try {
  throw new CustomError("this is a custom error");
} catch (error) {
  if (error instanceof CustomError) {
    console.log("hello, I am a custom error");
  }
}
        
try:
    risky()
except TypeError as t_error:
    print("this is a type error")
except Exception as error:  # catch-all 
    print("some other error")

# --- Custom exceptions: subclass Exception ---
class CustomError(Exception):
    pass # empty body — inherits everything

try:
    raise CustomError("this is a custom error")
except CustomError as c_error:
    print("hello, I am a custom error")
except Exception:
    print("caught by the generic handler")