Exception Handling in C++
Exception Handling in C++
1. try in C++
The try keyword represents a block of code that may throw an exception
placed inside the try block. It’s followed by one or more catch blocks. If an
exception occurs, try block throws that exception.
2. catch in C++
The catch statement represents a block of code that is executed when a
particular exception is thrown from the try block. The code to handle the
exception is written inside the catch block.
3. throw in C++
An exception in C++ can be thrown using the throw keyword. When a program
encounters a throw statement, then it immediately terminates the current
function and starts finding a matching catch block to handle the thrown
exception.
The try and catch keywords come in pairs: We use the try block to test some
code and If the code throws an exception we will handle it in our catch block.
Why do we need Exception Handling in C++?
The following are the main advantages of exception handling over traditional
error handling:
1. Separation of Error Handling Code from Normal Code: There are always
if-else conditions to handle errors in traditional error handling codes.
These conditions and the code to handle errors get mixed up with the
normal flow. This makes the code less readable and maintainable. With
try/catch blocks, the code for error handling becomes separate from the
normal flow.
3. Grouping of Error Types: In C++, both basic types and objects can be
thrown as exceptions. We can create a hierarchy of exception objects,
group exceptions in namespaces or classes, and categorize them
according to their types.
Examples of Exception Handling in C++
The following examples demonstrate how to use a try-
catch block to handle exceptions in C++.