Overview

MuPDF handles all its errors using an exception system. This is superficially similar to C++ exceptions, but (as MuPDF is written in C) it is implemented using macros that wrap the setjmplongjmp standard C functions.

It is probably best not to peek behind the curtain, and just to think of these constructs as being extensions to the language. Indeed, we have worked very hard to ensure that the complexities involved are minimised.

Unless otherwise specified, all MuPDF API functions can throw exceptions, and should therefore be called within a fz_tryfz_alwaysfz_catch construct.

Specific functions that never throw exceptions include all those named fz_keep_..., fz_drop_... and fz_free. This, coupled with the fact that all such `destructor' functions will silently accept a NULL argument, makes the fz_always block an excellent place to clean up resources used throughout processing.

The general anatomy of such a construct is as follows:


\begin{lstlisting}
fz_try(ctx)
{
/* Do stuff in here that might throw an except...
...xception thrown), execution
* continues after this block. */
}
\end{lstlisting}

The fz_always block is completely optional. The following is perfectly valid:


\begin{lstlisting}
fz_try(ctx)
{
/* Do stuff here */
}
fz_catch(ctx)
{
/* Clean up from errors here */
}
\end{lstlisting}

In an ideal world, that would be all there is to it. Unfortunately, there are 2 wrinkles.

The first one, relatively simple, is that you must not return from within a fz_try block. To do so will corrupt the exception stack and cause problems and crashes. To mitigate this, you can safely break out of the fz_try, and execution will pass into the fz_always block (if there is one, or continue after the fz_catch block if not).

Similarly, you can break out of a fz_always block, and execution will correctly pass into or after the fz_catch block as appropriate, but this is less useful in practise.

The second one, is more convoluted. If you do not wish to understand the long and complex reasons behind this, skip the following subsection, and just read the corrected example that follows. As long as you follow the rules given in the summary at the end, you will be fine.



Subsections