Advance Features
Errors
Beautiful way to handle errors!
Error Handling
syntax
return_type identifier(parameter) error_type {
}
- This syntax allows us to return an error code on failure.
- In this case, the
return_typeanderror_typewill be wrapped in an union behind the scene, which means only one block of memory will be allocated. error_typemust be defined usingenumtypeerror_typeis optional, however compiler will enforce checking if used- One function can have only one unique
error_typeenum. - Attempting to return a value that does not match the function's declared
return_typeor any of itserror_typewill result in compilation error.
Example:
enum MathError {
DivideByZero,
LogZero,
LogNegativeNumber,
# ...
}
float divide(float a, float b) MathError {
if(b == 0)
return MathError.DivideByZero;
return a / b;
}
int main(){
float result1 = divide(12, 3) otherwise (MathError error){
print(error.name);
}
float result2 = divide(12, 3) otherwise (error){ # <- MathError type specification is optional
if(error = MathError.DivideByZero){
print("cannot divide by zero\n");
}
}
return 0;
}