In Python I use try/except for error handling. How does EK9's try/catch compare?

← Error Handling and Exceptions · Ref: Q1014

EK9 uses try/catch/finally, similar to Python's try/except/finally but with different syntax.

Python:

  try:
      result = risky_operation()
  except ValueError as e:
      print(f'Error: {e}')
  finally:
      cleanup()

EK9:

  try
    result <- riskyOperation()
  catch
    -> ex as Exception
    stdout.println(`Error: ${$ex}`)
  finally
    cleanup()

KEY DIFFERENCES:

- catch uses -> for the exception parameter (data flowing IN to the handler)
- EK9 has a single Exception type (no ValueError, TypeError, etc.)
- No multiple except/catch blocks for different types
- The exception variable uses -> on its own line, like function parameters

TRY AS EXPRESSION:

Python has no try-expression. EK9 does:

  safeResult <- try
    riskyOperation()
  catch
    -> ex as Exception
    defaultValue()

Example

defines module qa.errorhandling.frompythonexception

  defines function

    riskyDivision() as pure
      ->
        numerator as Float
        denominator as Float
      <- rtn as Float: Float()

      if denominator?
        rtn: numerator / denominator

  defines program

    ExceptionDemo()
      stdout <- Stdout()
      stderr <- Stderr()

      // Like Python: try/except/finally
      try
        answer <- riskyDivision(10.0, 3.0)
        if answer?
          stdout.println(`Result: ${answer}`)
      catch
        -> ex as Exception
        stderr.println(`Caught: ${ex}`)
      finally
        stdout.println("Done")

      // Guard approach (simpler for functions that return unset)
      if safeAnswer <- riskyDivision(10.0, 0.0)
        stdout.println(`Got: ${safeAnswer}`)
      else
        stdout.println("Operation returned unset")

Common mistakes

E01010 — EK9 uses 'catch' not 'except'. The exception parameter uses '-> ex as Exception' on its own line, like function parameters.

Incorrect:

      except Exception as ex:
        stderr.println(`Error: ${$ex}`)

Correct:

      catch
        -> ex as Exception
        stderr.println(`Caught: ${ex}`)
Other ways to ask this
  • What is the EK9 equivalent of Python's try/except/finally?
  • How do I catch exceptions in EK9 coming from Python?
  • How does EK9 exception handling differ from Python?

Coming from another language?

Python developers: try/except becomes try/catch. The catch uses '-> ex as Exception' on its own line. EK9 has one Exception type, not a hierarchy.

Keywords: except, finally, catch, python, migration, try, exception