Éric
Éric

Reputation: 415

C and exceptions

In my the host part of my OpenCL code I've got a bunch of

  ret = clEnqueueWriteBuffer(command_queue, ...
  ret = clEnqueueWriteBuffer(command_queue, ...
  ret = clEnqueueWriteBuffer(command_queue, ...
  ...

and instead of each time doing

  if (ret != CL_SUCCESS)
    {
        printf("Error: Failed to write to source array!\n");
        exit(1);
    }

I'd like to know whether there is a way to somewhat wait for one "ret" to be unsuccessful to exit.

I'm aware (just aware, never used them) of the signal() and raise() functions but I'm not sure if I can use them here.

Upvotes: 0

Views: 167

Answers (3)

Aakash Anuj
Aakash Anuj

Reputation: 3871

The best way to handle exceptions in C is to make use of the perror call to get the result/status of the last performed action.

Here is a reference: http://en.cppreference.com/w/c/io/perror

Upvotes: 0

Jonathan Leffler
Jonathan Leffler

Reputation: 755016

Is there anything wrong with:

if ((ret = clEnqueueWriteBuffer(command_queue, ...)) != CL_SUCCESS ||
    (ret = clEnqueueWriteBuffer(command_queue, ...)) != CL_SUCCESS ||
    (ret = clEnqueueWriteBuffer(command_queue, ...)) != CL_SUCCESS)
{
    printf("Error: Failed to write to source array!\n");
    exit(1);
}
else
    ...do whatever it is that depends on everything else having succeeded...

And, if the error reporting code isn't going to use the value in ret, then you can do without the assignment and simplify that to:

if (clEnqueueWriteBuffer(command_queue, ...) != CL_SUCCESS ||
    clEnqueueWriteBuffer(command_queue, ...) != CL_SUCCESS ||
    clEnqueueWriteBuffer(command_queue, ...) != CL_SUCCESS)
{
    printf("Error: Failed to write to source array!\n");
    exit(1);
}
else
    ...do whatever it is that depends on everything else having succeeded...

Upvotes: 2

James Anderson
James Anderson

Reputation: 27486

The best way is to keep it simple stick an "if" statement after each call with a custom error message. Sound like a lot but look at the amount of code a "try/catch" block needs.

"signals" are there to handle hardware alerts and inter process communication. Using them to fake exceptions will lead you into a world of pain and misery.

Given that the "try/catch" is just a heavily disguised "goto" you could try:

  ret = clEnqueueWriteBuffer(command_queue, ...
  if (ret) goto catcher;
  ret = clEnqueueWriteBuffer(command_queue, ... 
  if (ret) goto catcher;
  ret = clEnqueueWriteBuffer(command_queue, ...
  if (ret) goto catcher;
  goto finalizer;
catcher:
  printf("Error: Failed to write to source array!\n");
        exit(1);
    }
finalizer:
   ..........

Upvotes: 2

Related Questions