Exceptions

This is an extract from a note that i'm learning from. I don't understand the try block and the first catch block in the code. Thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  int divide ( const int x , const int y) { 
    if (y == 0) 
    throw std :: runtime_exception (" Divide by 0! ");
    return x / y;
 }   
 
 void f( int x , int **arrPtr ) {  
     try {  
         *arrPtr = new int [ divide (5 , x) ];  
         }  
         catch ( bad_alloc & error ) {  
             cerr << " new failed to allocate memory ";  
             }  
             catch ( runtime_exception & error ) {    
                 cerr << " Caught error : " << error . what () ;  
                 }
                 } 
1
2
3
4
5
6
7
8
try
{
    //Try doing something
}
catch(//Error name) //If an error occurs
{
    //Handle the error
}


This is called error handling. What is done is, something is executed in the try statement that MIGHT cause some error under some circumstances. If there are no errors then the program continues as is. If there are errors then the catch statement is executed and maybe error messages are shown to the user or something alternative is done instead of crashing the program.

So in the code you gave, the try statement tries to allocate some memory. If it fails the catch statement executes depending on which error occurred. This is given by name in the catch statement parameter.
Last edited on
Topic archived. No new replies allowed.