[petsc-users] Proper way for exception handling

Zou, Ling lzou at anl.gov
Wed Oct 1 09:32:42 CDT 2025


Hi,

After updating to PETSc 3.23 (from a quite old version, ~3.8), I found that my old way of exception handling not working any more, on my Mac.
I would like to learn the proper way to handle exceptions in PETSc code.

Here is my pseudo code:

================================================================
PetscErrorCode SNESFormFunction(SNES, Vec, Vec, void*);
double my_function();
================================================================

double my_function()
{
  if (all_good)
return 1;
  else
  {
throw 199;
return 0;
  }
}

PetscErrorCode SNESFormFunction(SNES snes, Vec u, Vec r, void* ctx)
{
  double my_value = my_function();

  // compute residuals
}

int main(int argc, char **argv)
{
  Initialize_PETSc();

  double dt = 1, dt_min = 0.001;
  while (dt > dt_min)
  {
try
{
  SNESSolve(AppCtx.snes, NULL, AppCtx.u);
}
catch (int err)
{
  dt *= 0.5;
}
  }

  PetscFinalize();
}
================================================================

This piece of logic used to work well, but now giving me the following error:

Current time (the starting time of this time step) = 0..
        NL step =  0, SNES Function norm =  8.60984E+03
libc++abi: terminating due to uncaught exception of type int
Abort trap: 6

Q1: why this exception catch logic not working any more?
Q2: is there any good example of PETSc exception handling I can follow?

Best,
-Ling
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.mcs.anl.gov/pipermail/petsc-users/attachments/20251001/5426e7f5/attachment.html>


More information about the petsc-users mailing list