4

I am using a try-catch block like this one:

try {

    Texture heightmapTexture = Texture("Snow0101_7_M.jpg");

} catch (TextureLoadException exc) {
    std::cout << exc.what() << std::endl;
}

The thing is that I need to reuse the variable heightmapTexture further in my program. So I realized I can't do that because of the scope. Should I put the rest of the program inside the scope? For me that doesn't make any sense.

I also can't declare the variable outside of the scope because I have to initialize it. It has a constructor that only receives a string as input.

What would be the best solution?

I realize that I could use a pointer, but I am trying to avoid that (I am not really good at preventing memory leaks).

EDIT: Sorry, I was declaring the variable as a class Heightmap, which is wrong!, it is a texture object. But the problem is the same.

lhahn
  • 1,241
  • 2
  • 14
  • 40

2 Answers2

2

you'd normally want all your logic inside one try/catch context. Presumably if the loading of a texture fails, everything after it will fail also?

in which case you might be able to express the logic more neatly as:

try {
    Heightmap heightmapTexture = Texture("Snow0101_7_M.jpg");

    // do your work here

    // if anything fails fatally, throw

    // do you need to store the height map in an object?
    my_object.give_heightmap(std::move(heightmapTexture));
} 
// report failures here
catch (TextureLoadException& exc) { // note: by reference
    std::cout << exc.what() << std::endl;
}
catch (OtherReason& e) {
    // report the reason
}
catch(exception& e) {
  // other failures
}

A good way to think about exception handling is that an exception object is the explanation you are being given for a process or sequence failing, rather than each exception being an error code for one operation.

Richard Hodges
  • 68,278
  • 7
  • 90
  • 142
0

Declare your variable outside of the try-catch block like so.

Heightmap *heightmapTexture = null;

try {

    heightmapTexture = new Texture("Snow0101_7_M.jpg");

} catch (TextureLoadException exc) {
    std::cout << exc.what() << std::endl;
}