Catch an exception from a division operation and handle it.

← Control Flow · Ref: Q1154

catch uses -> parameter syntax; ex.reason() gets the message:

  try
    result <- 100 / 5
    stdout.println(`Result: ${result}`)
  catch
    -> ex as Exception
    stdout.println(`Error: ${ex.reason()}`)
  finally
    stdout.println("cleanup")

The catch block declares the exception with -> (data-in port). The finally block always runs. Use ex.reason() not getMessage().

See Q1155 for finally details. See Q1156 for nested try/catch.

Example

defines module qa.controlflow.trycatchbasics

  defines program

    TryCatchBasicsDemo()
      stdout <- Stdout()

      //Safe division
      try
        result <- 100 / 5
        stdout.println(`100 / 5 = ${result}`)
      catch
        -> ex as Exception
        stdout.println(`Error: ${ex.reason()}`)

Common mistakes

E01010 — EK9 uses indentation, not braces. The catch parameter uses -> syntax. Use .reason() not .getMessage().

Incorrect:

      catch (Exception ex) {
        System.out.println(ex.getMessage());
      }

Correct:

      catch
        -> ex as Exception
        stdout.println(`Error: ${ex.reason()}`)
Other ways to ask this
  • I need to handle a runtime error using try/catch in EK9
  • In Java I'd use try-catch with specific exception types. Write the EK9 equivalent
  • Given a division that might fail, catch the exception and print an error message
  • Handle an arithmetic error gracefully using try and catch blocks

Coming from another language?

Java: try { } catch (Exception e) { }. Python: try: except Exception as e:. EK9: try / catch -> ex as Exception.

Keywords: handle, try, divide, catch, error, exception