Exception handling in C ++

Tram Ho

Exception handling in C ++

1. Definition

One of the advantages of C ++ over C is Exception Handling. Exceptions are runtime abnormalities or abnormal conditions encountered by the program during execution. There are two types of exceptions:

  • Synchronous + Asynchronous For example, outside of the Control program, Disk error program, etc. C ++ provides the following specialized keywords for this purpose.

try: represents a block of code that can throw an exception.

Catch: represents a block of code that is executed when throwing a specific exception.

throw: Used to throw an exception. Also used to list exceptions that a function throws, but does not handle itself.

2. Advantages

  • Separate error handling code from Normal Code: In traditional error handling codes, there are always other conditions for error handling. These conditions and the code for error handling are mixed with the normal thread. This makes the code less readable and maintainable. With try – catch blocks, the code for handling errors becomes separate from the normal thread.
  • Function / methods can handle any exception they choose: A function may raise multiple exceptions, but may choose to handle some exceptions. Other exceptions that are thrown, but not captured, can be handled by the caller. If the caller chooses not to capture them, the exceptions are handled by the caller’s caller. In C ++, a function can specify the exceptions it throws using the throw keyword. The caller of this function must handle the exception in some way (by reassigning or catching it).
  • 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 classify them by type.

3. Exception handling

a. The following is a simple example to show exception handling in C ++. The output of the program explains the execution flow of try-catch blocks:


b. There is a special catch block called ‘catch all’ catches (…) to catch all kinds of exceptions. For example, in the following program, an int is thrown as an exception, but there is no catch block for int, so the Catch (…) block will be executed.


c. Default type conversions do not occur for primitive types. For example, in the following program, a rocket is not completely converted into int


4. Conclusion

Try-catch is a very important process in C ++, helping your program or project to avoid unnecessary errors (these errors must be ignored or will be notified, such as a division). number for 0). If you are proficient in try-catch it will help you a lot in the process of working on large projects. Good luck!

Share the news now

Source : Viblo