Skip to content

错误码 ​

项目链接:GitHub · VM 错误源码

概述 ​

MaìLang 使用 Result 类型进行错误处理,不抛出异常。所有可能失败的操作都返回 Result<T, E> 或 Option<T>。

运行时错误 ​

VmError ​

错误代码说明示例
StackOverflow栈溢出递归过深
StackUnderflow栈下溢弹出空栈
TypeError类型错误"a" - 1
UndefinedVariable未定义变量println(x)
UndefinedFunction未定义函数foo()
UndefinedProperty未定义属性obj.bar
WrongArgumentCount参数数量错误add(1)
DivisionByZero除以零1 / 0
IndexOutOfBounds索引越界arr[100]
InvalidOperation无效操作null + 1
RuntimeError运行时错误通用错误

CompilerError ​

错误代码说明
UndefinedVariable未定义的变量
TooManyConstants常量过多(超过 65536)
TooManyLocals局部变量过多(超过 256)
TooManyUpvalues闭包变量过多(超过 256)
InvalidAssignmentTarget无效的赋值目标
BreakOutsideLoopbreak 在循环外
ContinueOutsideLoopcontinue 在循环外
ReturnOutsideFunctionreturn 在函数外
DuplicateFunction重复的函数名
DuplicateClass重复的类名
DuplicateTrait重复的 trait 名

ParseError ​

错误代码说明
UnexpectedToken意外的 token
UnexpectedEof意外的文件结束
InvalidExpression无效的表达式
InvalidStatement无效的语句
ExpectedIdentifier期望标识符
ExpectedTypeAnnotation期望类型标注
ExpectedExpression期望表达式
ExpectedPattern期望模式
ExpectedBlock期望代码块
InvalidAssignmentTarget无效的赋值目标
InvalidFunctionDefinition无效的函数定义
InvalidClassDefinition无效的类定义
InvalidPattern无效的模式

LexerError ​

错误代码说明
UnexpectedCharacter意外的字符
UnterminatedString未结束的字符串
UnterminatedChar未结束的字符
InvalidEscapeSequence无效的转义序列
InvalidNumber无效的数字格式
InvalidUnicodeEscape无效的 Unicode 转义

AnalyzerError ​

错误代码说明
UndefinedVariable未定义的变量
UndefinedFunction未定义的函数
UndefinedClass未定义的类
UndefinedTrait未定义的 trait
TypeMismatch类型不匹配
ImmutableAssignment对不可变变量赋值
ConstantAssignment对常量赋值
WrongArgumentCount参数数量错误
MethodNotFound方法未找到
PropertyNotFound属性未找到
MissingTraitMethod未实现 trait 方法
CircularInheritance循环继承
ThisOutsideMethodthis 在方法外使用
SuperOutsideSubclasssuper 在子类外使用
DuplicateDefinition重复定义
UnusedVariable未使用的变量

错误处理最佳实践 ​

使用 match 处理错误 ​

let result = match divide(10.0, 0.0) {
    Ok(v) => println("结果: {v}"),
    Err(e) => println("错误: {e}")
}

使用 ? 操作符 ​

? 已支持:对 Ok/Some 解包,遇 Err/None 从当前函数提前返回。

fn process() -> Result<str, str> {
    let value = divide(10.0, 0.0)?  // 如果错误,提前返回
    Ok("处理完成")
}

自定义错误类型 ​

尚未支持 enum 关键字。当前用字符串错误码或类承载错误信息:

fn do_something() -> Result<str, str> {
    // ...
    return Err("NotFound: file.txt")
}

下一步 ​