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 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 an Exception, log "failed to send to Ali because no stamp." So, nobody cared in this example who could throw. They simply did their tasks. Of course, it's not always as simple in practice but you almost never need to catch exceptions from individual functions.

To contrast, C's error handling is too cumbersome as every single programming step must at least be two lines: first do it and then check the error code. (Go famously claims that it followed C in this regard for simplicity. Since they made other claims and have shown ignorance especially at the time of Go's introduction, I will never believe Go adopted C's error handling for simplicity.)

Ali

Reply via email to