Exception handling

SO this may be the last time I ask a question in a while... I think I got the hang of exceptions now, code-wise, but there is one thing I kind of don't get: Where do I place these exception handlers?

Consider this code snippet:

1
2
3
4
5
6
7
8
9
10
11
 std::string adminLine;
    aFile.open("admin.txt");
    if ( aFile.is_open() ) {
      while ( aFile.good() ) {
        getline (aFile, adminLine);
        std::cout << adminLine << std::endl;
      }
      aFile.close();
    }
    else
      std::cout << "\nFile could not be found.\n";


Do I enclose it around a try block or do I create a function to call where I put that code in a try block? At what point should I throw an exception? Should I throw the exception after an if-statement enclosing the code returns false? I'm actually rather confused regarding how to actually implement this feature.

Any pointers for me to work with would be great, thanks! =)
The whole point of exceptions is that you can write code that just assumes everything is working. The code that throws the exception should not be aware of the "bigger picture" code that is actually coordinating a larger task.

This is particularly useful when you have a task which requires a series of events to happen in order. If any one of those events fails, you can't proceed with the overall job.

Compare the error-checking version:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
bool DoALargeJob()
{
  if( Job1() != SUCCESS )
  {
    Cleanup();
    return false;
  }

  if( Job2() != SUCCESS )
  {
    Cleanup();
    return false;
  }

  if( Job3() != SUCCESS )
  {
    Cleanup();
    return false;
  }
}


vs. the Exception version:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
bool DoALargeJob()
{
  try
  {
    Job1();  // assuming these functions now throw exceptions upon failure
    Job2();
    Job3();
    return true;
  }
  catch(...)
  {
    Cleanup();
    return false;
  }
}



Figuring out exactly where and how to apply this can be tricky and takes some time to get used to (I'm still not great at it, myself).


It's hard to give advice based on the code snippit you provided because I can't tell what the error situation would be.
I'll try to see if I can progress at all by referring to your post. What I want to do is throw an exception if the program fails to read in the file "admin.txt".
Topic archived. No new replies allowed.