Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++ what are the benefits of using exceptions and try / catch instead of just returning an error code?

I've programmed C and C++ for a long time and so far I've never used exceptions and try / catch. What are the benefits of using that instead of just having functions return error codes?

like image 421
KPexEA Avatar asked Sep 11 '25 02:09

KPexEA


2 Answers

Possibly an obvious point - a developer can ignore (or not be aware of) your return status and go on blissfully unaware that something failed.

An exception needs to be acknowledged in some way - it can't be silently ignored without actively putting something in place to do so.

like image 147
Martin Avatar answered Sep 12 '25 15:09

Martin


The advantage of exceptions are two fold:

  • They can't be ignored. You must deal with them at some level, or they will terminate your program. With error code, you must explicitly check for them, or they are lost.

  • They can be ignored. If an error can't be dealt with at one level, it will automatically bubble up to the next level, where it can be. Error codes must be explicitly passed up until they reach the level where it can be dealt with.

like image 44
James Curran Avatar answered Sep 12 '25 16:09

James Curran