Exceptions names list

Ali Çehreli acehreli at yahoo.com
Tue Nov 16 05:17:40 UTC 2021


On 11/15/21 3:00 PM, pascal111 wrote:
 > On Monday, 15 November 2021 at 22:44:35 UTC, Ali Çehreli wrote:
 >> On 11/15/21 2:28 PM, pascal111 wrote:
 >> > [...]
 >> "throw" statement
 >> > [...]
 >>
 >> Such a list is not very useful. Normally all we need is Exception and
 >> occasionally one or two other specific types.
 >>
 >> [...]
 >
 > What if I expect more than one exception a function can do in "try"
 > block,

One benefit of exceptions is separating actual work from error handling. 
Code can be written as if everything will go well. If not, a higher 
level function may catch the exception and e.g. start over. So, no 
matter how many different kinds of exceptions may be thrown or no matter 
how complicated a function is, we just do the work:

void foo() {
   work();
   moreWork();
   etc();
}

Some higher level function may have a try-catch, which may catch a 
potential exception. Fine:

// An intermediate function that uses foo:
void zar() {
   foo();
}

// A higher level function that uses the intermediate function:
void bar() {

   // Try until successful
   while (true) {
     try {
       zar();

       // It worked! Let's leave.
       return;

     } catch (Exception ex) {
       // Something bad happened
       // Let's try again...
     }
   }
}

bar() catches all exceptions without caring what exact type they are. 
(In practice, for me, bar() is usually main(), the top level function.)

 > and I need more than one "catch" block after that, so I'll need
 > to define the exception, or you can turn around this with some way?

Well, if you *need* to handle a particular exception specially, then you 
have to have a specific catch clause for that exception. Otherwise, a 
single catch(Exception) is sufficient for most programs.

That is possible because all exceptions inherit from Exception:

class MyException : Exception {
   // ...
}

That definition means "MyException is an Exception", which allows 
MyException objects to be caught as Exceptions as well.

Exceptions are a useful tool but they are not suitable for all cases. 
Maybe you have such a case.

Ali




More information about the Digitalmars-d-learn mailing list