Examples

Exceptions

CellSpeak has exception handling. Exceptions are used for events that happen inside a cell but are best processed outside the normal control flow, either because they are cumbersome to check for every time or because they simply cannot be handled in a meaningful way at the level where they occur.

Every code unit in CellSpeak - ie a function, a message handler, a constructor, a destructor or a design itself can have one exception table. The exception table lists the exceptions that you want to handle in the code unit.

Exceptions are always handled in the context of the cell where they occur. Exceptions are a flow control mechanism - with stack unwinding and handler selection - that only make sense during the execution of code for a cell. A cell can of course always signal an exception to another cell by sending a message from the handler for example.

Exceptions can be generated by the OS (such as IntDivideByZero or AccessViolation) or in the CellSpeak code by using the 'raise' statement. Exceptions can have parameters.

Exceptions that are not handled are propagated to the next level - up to the level of the cell. If the exception is not handled at that level, then the cell can be destroyed depending on the graveness of the exception.

16 Exceptions.celsrc
-.-
	Exceptions
	
	In this example we show how the exception mechanism in CellSpeak functions with the 
	simple example of a division by zero.
-.-
use Windows, Math, Strings, Editor, System

-- a simple function
function IntegerDivision(int u, int v) out int is 
	-- This is all the useful work function does !
	return u/v
	
	-- The exception table of the function
	catch 	
		-- This exception is generated by the OS and redirected to this handler
		IntDivideByZero do
			
			-- we send a message to the terminal
			system <- println("IntDivideByZero caught in function")
			
			-- for this example we just raise another exception !
			raise DivisionByZero( u, v)
		end		
	end
end

design ExceptionExamples is

	constructor is 
		-- We create an output cell.
		cell Window = create MenuWindow("Exceptions Example")
		system <- stdout.Set(Window)
		
		-- This will generate an exception..
		var c = IntegerDivision(9,0)
		
		-- This statement will not be reached if an exception fires, because of the exception.
		system <- println("End of the exception example")
	end
	
	destructor is 
		system <- println("help")
	end

	-- The exception table of the cell (we can use a lambda arrow for single expression exception handling)
	catch 
		DivisionByZero(int r, int s) 	=> system <- println("DivisionByZero caught in cell, two parameters: [r]/[s]")

		-- Just another examle		
		OutOfScratchPadMemory 			=> system <- println("out of memory")
		
		-- if we are not handling an exception, we can still intercept all exceptions with a default exception (comment out DvisionByZero to see it at work)
		default (utf8 Name) 			=> system <- println("Exception [Name] was thrown in ExceptionExamples")
	end 
end