Cava provides limited exception handling and does not support try-catch blocks. Cava automatically detects three runtime exception types: division by zero, array index out of bounds, and null pointer access. When an exception occurs, Cava stops execution and returns an error message. Guard against exceptions by validating inputs before performing division, array access, or object member access.
Division by zero
Integer division by zero throws an exception. Floating-point division by zero does not.
Exception trigger:
int b = 0;
int a = 1 / b; // Throws an exception: integer division by zero.No exception (floating-point):
double c = 0;
double b = 1 / c; // Does not throw an exception.
int a = 1 / c; // Does not throw an exception.Guard pattern: Check that the divisor is non-zero before dividing.
int b = 0;
int a = 0;
if (b != 0) {
a = 1 / b;
}Array index out of bounds
Accessing an array with an index below 0 or at or above array.length throws an exception.
Exception trigger:
int[] a = new int[10];
a[-1] // Invalid. The index is below the lower bound.
a[10] // Invalid. The index exceeds the upper bound.Guard pattern: Validate that the index is greater than 0 and less than a.length before accessing the array.
int[] a = new int[10];
int idx = 10;
if (idx > 0 && idx < a.length) {
int b = a[idx];
}Null pointer access
Accessing a member of a null object throws an exception.
Exception trigger:
Person student = null; // Assume Person is a predefined class.
student.setAge(15); // Throws an exception: null pointer access.Guard pattern: Check that the object is non-null before accessing its members.
Person student = null;
if (student != null) {
student.setAge(15);
}Manually throw an exception
Use Abort.abort() to stop execution immediately from within a Cava script. Pass a message string to include details in the returned error.
Abort.abort();
Abort.abort("exception");