Suppose there is a class for working with the database. There are methods of this class that handle possible errors through if, writing the text of the error that occurred to the lastError class variable, sending a signal that an error has occurred and returning what the method should return in case of an error.
bool insertIntoSomeTable() { // Π½ΠΎΡΠΌΠ°Π»ΡΠ½ΡΠΉ Ρ
ΠΎΠ΄ Π²ΡΠΏΠΎΠ»Π½Π΅Π½ΠΈΡ ΠΏΡΠΎΠ³ΡΠ°ΠΌΠΌΡ if( ΠΎΡΠΈΠ±ΠΊΠ° ΠΏΠΎΠ΄ΠΊΠ»ΡΡΠ΅Π½ΠΈΡ ) { lastError=ΠΎΡΠΈΠ±ΠΊΠ° ΠΏΠΎΠ΄ΠΊΠ»ΡΡΠ΅Π½ΠΈΡ; emit errorHasOccured(lastError); return false; } // Π½ΠΎΡΠΌΠ°Π»ΡΠ½ΡΠΉ Ρ
ΠΎΠ΄ Π²ΡΠΏΠΎΠ»Π½Π΅Π½ΠΈΡ ΠΏΡΠΎΠ³ΡΠ°ΠΌΠΌΡ if( ΡΠ΅ΡΠ²Π΅Ρ Π½Π΅ ΠΌΠΎΠΆΠ΅Ρ ΠΏΡΠΈΠ½ΡΡΡ Π΄Π°Π½Π½ΡΠ΅) { lastError=ΡΠ΅ΡΠ²Π΅Ρ Π½Π΅ ΠΌΠΎΠΆΠ΅Ρ ΠΏΡΠΈΠ½ΡΡΡ Π΄Π°Π½Π½ΡΠ΅; emit errorHasOccured(lastError); return false; } // Π½ΠΎΡΠΌΠ°Π»ΡΠ½ΡΠΉ Ρ
ΠΎΠ΄ Π²ΡΠΏΠΎΠ»Π½Π΅Π½ΠΈΡ ΠΏΡΠΎΠ³ΡΠ°ΠΌΠΌΡ if( ΠΎΡΠΈΠ±ΠΊΠ° Π²ΡΠΏΠΎΠ»Π΅Π½ΠΈΡ Π·Π°ΠΏΡΠΎΡΠ° ) { lastError=ΠΎΡΠΈΠ±ΠΊΠ° Π²ΡΠΏΠΎΠ»Π΅Π½ΠΈΡ Π·Π°ΠΏΡΠΎΡΠ°; emit errorHasOccured(lastError); return false; } //ΠΈ ΡΠ°ΠΊ Π΄Π°Π»Π΅Π΅ return true } As a result, these ifs are very cluttered with method code. Is it normal practice if I redefine my exception class for the database and rewrite the method like this:
bool insertIntoSomeTable() { try { // Π½ΠΎΡΠΌΠ°Π»ΡΠ½ΡΠΉ Ρ
ΠΎΠ΄ Π²ΡΠΏΠΎΠ»Π½Π΅Π½ΠΈΡ ΠΏΡΠΎΠ³ΡΠ°ΠΌΠΌΡ if( ΠΎΡΠΈΠ±ΠΊΠ° ΠΏΠΎΠ΄ΠΊΠ»ΡΡΠ΅Π½ΠΈΡ ) { throw DatabaseException("ΠΡΠΈΠ±ΠΊΠ° ΠΏΠΎΠ΄ΠΊΠ»ΡΡΠ΅Π½ΠΈΡ"); } // Π½ΠΎΡΠΌΠ°Π»ΡΠ½ΡΠΉ Ρ
ΠΎΠ΄ Π²ΡΠΏΠΎΠ»Π½Π΅Π½ΠΈΡ ΠΏΡΠΎΠ³ΡΠ°ΠΌΠΌΡ if( ΡΠ΅ΡΠ²Π΅Ρ Π½Π΅ ΠΌΠΎΠΆΠ΅Ρ ΠΏΡΠΈΠ½ΡΡΡ Π΄Π°Π½Π½ΡΠ΅) { throw DatabaseException("ΡΠ΅ΡΠ²Π΅Ρ Π½Π΅ ΠΌΠΎΠΆΠ΅Ρ ΠΏΡΠΈΠ½ΡΡΡ Π΄Π°Π½Π½ΡΠ΅"); } // Π½ΠΎΡΠΌΠ°Π»ΡΠ½ΡΠΉ Ρ
ΠΎΠ΄ Π²ΡΠΏΠΎΠ»Π½Π΅Π½ΠΈΡ ΠΏΡΠΎΠ³ΡΠ°ΠΌΠΌΡ if( ΠΎΡΠΈΠ±ΠΊΠ° Π²ΡΠΏΠΎΠ»Π΅Π½ΠΈΡ Π·Π°ΠΏΡΠΎΡΠ° ) { throw DatabaseException("ΠΎΡΠΈΠ±ΠΊΠ° Π²ΡΠΏΠΎΠ»Π΅Π½ΠΈΡ Π·Π°ΠΏΡΠΎΡΠ°"); } //ΠΈ ΡΠ°ΠΊ Π΄Π°Π»Π΅Π΅ return true } catch(DatabaseException& e) { lastError= e.what(); emit errorHasOccured(lastError); return false; } } Also, of course, you can make this method void; in the method itself, do only throw, and catch errors somewhere higher. But I would not really like to do that. In general, is it ok to use the above option?