2.5.4 Throwing Other Values
In the previous examples, you saw how to handle exceptions that C++ may throw, and exceptions that you can throw. In this example, you are going to look at how to use the try/catch block to throw variables.
Throwing a Value
Just like you can throw an exception with a message, you can also throw a value and then catch that value type.
For example, if you wanted to throw a string, your try/catch may look something like this.
Notice that you just throw the variable and the catch is catching a string value. You can use the same catch for multiple throws, or have different catches for different variable types, but you should not have multiple catches for the same variable type. If you do, C++ will only look at the first value.
Examples:
A Note On Strings
A string
variable needs to be caught with a string
type:
If you throw a string literal, you actually need to catch it with a char const*
type in C++:
Here is a quick example:
Why use Try/Catch?
In these examples above, you may ask why would you throw a variable instead of just handling the condition inside an if
statement. It is a good question and there are times when an if/else block may make more sense than a try/catch block.
Sometimes the answer comes down to personal choice. One programmer may feel more comfortable with one block over another. Sometimes it may make more sense to use the try/catch when you have additional code that needs to be run after an if
block, but you don’t want to run it for the values that you catch in the error. Throwing a bad value out allows your main code block to continue without the values that caused an error. You will notice this in the following example.
Last updated