Neon
← Back to Defining functionsNext: Parallel programming →

Error Handling

Neon uses exceptions to handle errors. You can catch exceptions with try...except blocks or raise them manually.


1. Built-in Exceptions

Exception Description
SyntaxError Syntax error in code.
FileSystemError File read/write failure.
UnmeasurableObject len() called on a non-measurable object.
UndefinedVariable Using an undefined variable.
IncorrectFunctionCall Function called incorrectly.
MemoryError Memory allocation failure.
NonIndexableObject Trying to index a non-list/string.
IncorrectIndex Index is not a positive integer.
OutOfRange Index exceeds object size.
IncorrectType Type mismatch in an operation.
DivisionByZero Division by zero.
UnknownError Generic unknown error.
AssertionFailed assert() failed.
DefinitionError Incorrect container definition.
KeyboardInterrupt User pressed Ctrl-C (or ON on TI-EZ80).
NotImplemented Feature not implemented (e.g., initGraphics on non-TI-EZ80).

2. try...except Blocks

Syntax

try
    # Code that might raise an exception
except (Exception1, Exception2, ...) do
    # Code to run if an exception is raised
end

Examples

# Basic try-except
try
    x = 1 / 0  # Division by zero
except (DivisionByZero) do
    print("Cannot divide by zero!")
end

# Multiple exceptions
try
    print(1 + "hello")  # Type error
except (IncorrectType, DivisionByZero) do
    print("Math error occurred!")
end

# Catch any exception (no exception specified)
try
    # Risky code
    print(undefined_var)
except () do
    print("An error occurred, but we don't know which one.")
end

# Multiple except blocks
try
    x = int("abc")  # Will raise IncorrectType
except (DivisionByZero) do
    print("Division error")
except (IncorrectType) do
    print("Type error: cannot convert to int")
end

3. Raising Exceptions Manually

Use raise() to trigger an exception.

Syntax

raise(ExceptionType, "Error message")

Example

function divide(a, b) do
    if (b == 0) then
        raise(DivisionByZero, "Cannot divide by zero!")
    end
    return (a / b)
end

try
    divide(10, 0)
except (DivisionByZero) as e do
    print("Error: " + e)  # Note: e may not capture the message directly
end

4. Creating Custom Exceptions

Use createException() to define new exception types.

Example

# Create a custom exception
MyError = createException("MyCustomError")

# Raise it
try
    raise(MyError, "Something went wrong!")
except (MyError) do
    print("Caught a custom error!")
end

5. The assert Function

Use assert() to check conditions and raise AssertionFailed if they are False.

Example

x = 5
assert(x > 0)  # Passes (no error)
assert(x > 10) # Raises AssertionFailed

← Back to Defining functionsNext: Parallel programming →