Exceptions
Introduction
Exception handling provides simpler (less error prone) and more logical (separate detection and handling) error handling than traditional return value based error handling used in most kernels.Exceptions use KTRY/KCATCH/KFINALLY
blocks of code, to delimit the various stages of exception management:
EXCEPTION_DEF(MyException,ParentException)
- Defines an exception (MyException
) that can be thrown and caught, which is a subclass of the parent exception (ParentException
).KTRY
- The block of code following is executed.KCATCH>
- The try block can catch zero or more exception types specified in the correspondingKCATCH
blocks. EachKCATCH
block handles exceptions of that type (and sub-type) only.KFINALLY
- The finally block is executed regardless of whether an exception was thrown or not. It is used to clean up any resources that may have been used in the try block, such as free'ing allocated memory or unlocking resources.KTHROW/KTHROWF
- Throws an exception, with an error message (formatted usingprintf
like arguments inKTHROWF
case.)
Example
The following example shows how exceptions are used:
/* Exception is a standard exception type */ EXCEPTION_DEF(ParentException,Exception); EXCEPTION_DEF(MyException,ParentException); ... void DoSomethingThatMightThrowAnException(...) { ... Checks can throw exceptions to indicate invalid data ... check_arguments(); ... Blah blah blah ... if (SomethingWentWrong) { KTHROW(MyException, "It all went horribly wrong"); } } void Function() { KTRY { ... Do stuff ... DoSomethingThatMightThrowAnException(...); ... This stuff won't be reached on exception above ... } KCATCH(MyException) { ... Oops - log an error ... ... Recover the situation if possible ... } KCATCH(Exception) { ... Oops - log more generic error ... } KFINALLY { ... Release any resources ... } }