Get the App
SLTechnology News&Howtos  ›  Development  › 

Example Analysis of exception handling in C++

Shulou Source: shulou.com Published: 2022-06-03 15:03:13 10月01日 Update

This article mainly introduces C++ exception handling example analysis, the article is very detailed, has a certain reference value, interested friends must read!

I. Background

Some exceptions are encountered when the program is running, such as:

Divide by 0;

When space is allocated dynamically with the new operator, there is not enough space to allocate it;

Subscript out of bounds when accessing array elements; file does not exist when open for reading.

These exceptions, if not detected and handled, are likely to cause the program to crash.

"Handling" can mean giving an error message and letting the program continue along an error-free path, or it can mean having to end the program but doing something necessary before it ends, such as writing data in memory to files, closing open files, freeing dynamically allocated memory space, and so on.

C++ exception handling

C++ introduces exception handling.

Exceptions provide a way to transfer program control. C++ exception handling involves three keywords: try, catch, and throw.

throw: When a problem occurs, the program throws an exception. This is done by using the throw keyword.

catch: Catch exceptions with exception handlers where you want to handle the problem. The catch keyword is used to catch exceptions.

The code in the try: try block identifies the specific exception that will be activated. It is usually followed by one or more catch blocks.

for example

#include #include using namespace std; int main () { try { throw 1; throw "error"; } catch (const char* str) { cout

Tags: Processing program caching code file type key keyword object space result allocation run example analysis example memory content dynamic place Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft Shulou Information NVidia OPPO Reno Apple