Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use try/catch in C++

Shulou Source: shulou.com Published: 2022-06-01 20:48:01 11月14日 Update

This article mainly introduces "how to use try/catch in C++". In daily operation, I believe many people have doubts about how to use try/catch in C++. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts about "how to use try/catch in C++". Next, please follow the editor to study!

E.18: minimum explicit use of try/catch

Reason (reason)

The structure of try/catch is lengthy, and its non-trivial usage is error-prone. Try/catch can be seen as a signal of non-systematic and low-level resource management or error handling.

Example, Bad (negative example)

Void f (zstring s)

{

Gadget* p

Try {

P = new Gadget (s)

/ /...

Delete p

}

Catch (Gadget_construction_failure) {

Delete p

Throw

}

}

The code is messy. A memory leak may occur in the original pointer in the try code block. Not all exceptions are handled. It is certainly a mistake to delete an object opportunity that failed to build. Better practices:

Void f2 (zstring s)

{

Gadget g {s}

} Alternatives (other options)

Proper resource handles and RAII

Use resource handles and RAII correctly.

Finally

Finally processing

At this point, the study on "how to use try/catch in C++" is over. I hope I can solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Tags: Caching learning processing code more resources errors help verbose messy primitive practical mundane minimum next signal practice memory reason reverse Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology Microsoft Apple Shulou Tech Info vpn