C++ Exception HandlingAlthough it is not required, the makers of ClanLib recommend that you use C++ exception handling to catch any errors (no pun intended <G>). Even if you aren’t going to use this in your ClanLib apps, you should still understand it, as it is helpful when reading source code from ClanLib apps, and some of ClanLib’s source itself. For creating your own apps, you will be using the try {} and catch {} statements, but I’ll cover the throw statement too in case you run in to it (or are just curious). To put simply, try {} tries ever statement in the code block (hmmm, imagine that…), and catch {} catches any errors that were thrown (with throw {} inside functions) from within the try {} statement. Sound confusing? Well, it isn’t, I just felt like making it sound that way <BG>. Take a look at the following example that would be placed in the regular main() function:
Okay, first of all, take a look at the std:: thing in front of cout. Now, not all compilers require this, but the ClanLib guys like to just to be safe on as many platforms as possible. I couldn’t agree more. So just get used to it. Moving on… In the try {} statement, we execute the_function(), and if it works, it’s all good. If not, we use the catch {} statement to get the error that occurred (in this case in char * format) and do some output or whatever else you’d want to do. But how do you catch the error? Well, I’m glad you asked! Take a look at the definition for the_function():
Here, you have a pointer (cleverly named ptr) that is obviously global. We test to make sure it is a valid pointer, and if not, we throw the message with the throw statement. That’s all there is to it. Now, if you wanted some real good exception handling, you’d probably want to make your own error classes, but I’ll leave that up to you. Oh yes. This has nothing to do with exception handling, really, but in case you were unaware of this before, you should always set up sentinels in your header files to prevent compiler errors. Take a look:
If you look at any of the ClanLib headers, you’ll see that they all have this on them. I recommend you do this with all of your headers as well, as it is often a lot easier than simply not including a header in one or more source files. |
||||||||||||||||||||