On Thursday, 1 June 2017 at 15:17:32 UTC, Ali Çehreli wrote:
On 06/01/2017 06:26 AM, Vasileios Anagnostopoulos wrote:

> how do I know that a function "may throw" an
> exception in order to use a try/catch/finally block? This is
my biggest
> problem (sorry, coming from a java/C background).

I come from a C++ background so the advices may be different from Java's.

The liberating thing about exceptions is that you simply do not catch them. In fact, you're adviced against catching them unless you want to or can do something when they are thrown.

If you think that way, you write your code to do its resource management automatically with destructors, scope statements (scope(exit), scope(exception), and scope(success)), etc.

Say, you want to send a letter by performing certain steps: grab a paper, write the letter, grab an envelope, put the


Let us emulate this as function calls with void


void sendEmailToAli() {

grabAPaper();
writeALetter();
grabAnEnvelope();
putTimeStamp(); //throws an Exception, function not in my control, residing in a dll
putToMailBox();

}

letter inside, oops, there is no stamp. Throw an exception... If such low or intermediate level functions have no idea what the higher layer application code wants to do in this case, they simply throw. N layer up, a function would want to catch



//If I knew about the exception
//I could recover, because exceptions
//signal recoverable errors

void haveToCommunicateWithAli() {
try {

sendEmailToAli();

} catch(Exception e) {

goPersonallyToAli();

}
}


//If I do not know

void haveToCommunicateWithAli() {
sendEmailToAli();
}

//can blow-up after code has shipped
//and have no chance to recover


What shall I do in this case? Thank you in advance.

Vasileios

Reply via email to