[petsc-users] Proper way for exception handling

Zou, Ling lzou at anl.gov
Wed Oct 1 10:46:48 CDT 2025


Although I haven’t tried yet. Does it make sense and should it work to change the code this way?

================================================================
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)
{
  Try
  {
my_value = my_function();
  }
  Catch (int err)
  {
    return PETSC_ERR_NOT_CONVERGED;
  }

  // compute residuals

  return PETSC_SUCCESS;
}

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

  double dt = 1, dt_min = 0.001;
  while (dt > dt_min)
  {
SNESSolve(AppCtx.snes, NULL, AppCtx.u);

SNESGetConvergedReason(AppCtx.snes, &(AppCtx.snes_converged_reason));

if (not_converged)
  dt *= 0.5;
}
  }

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



From: petsc-users <petsc-users-bounces at mcs.anl.gov> on behalf of Zou, Ling via petsc-users <petsc-users at mcs.anl.gov>
Date: Wednesday, October 1, 2025 at 9:33 AM
To: PETSc <petsc-users at mcs.anl.gov>
Subject: [petsc-users] Proper way for exception handling
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/7138ef1d/attachment-0001.html>


More information about the petsc-users mailing list