KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Error Handling a One Line Expression with Try() Statement
PRODUCT: 4D | VERSION: 20 R | PLATFORM: Mac & Win
Published On: November 25, 2024

As of 4D v20 R4, 4D has added error handling in the form of a Try(expression) statement. This statement works similarly to a Try Catch block except that it is geared toward a single line of code. This can allow the handling of errors without the need for a try catch block or an error-handling method.

When using this statement, if an error occurs within the expression's execution, instead of an error dialog showing up, Try() will return either the last evaluated value or the value will become Undefined.

The following example shows a simple instance of attempting to access an element of an array that does not exist. However, it can be used for many one-line statements that have the possibility of throwing errors such as accessing files in the case of a file that does not exist or division in the case of division by zero.

ARRAY TEXT($products; 3)
$products{1}:="Pencils"
$products{2}:="Stapler"
$products{3}:="Paper"

$product:=Try($products{4}) || "Invalid Product"

$res:="Product: "+$product

ALERT($res)