I am coding a game boy disassembler in C++. The program (simplified here) converts a vector of byte into an assembly instruction and print it.
To do so, it iterates through the vector of bytes (char) with an iterator. I noticed that with the it!=char_vect.end()
condition, there is the risk that the iterator goes out from the vector. So I have to check that I do not get out of the vector at each iteration and if it occurs, I throw an error.
#include <iostream>
#include <vector>
int disassemble(std::vector<char>::iterator& it){
int opcode = *it;
int opbytes = 1; //number of bytes used by the operator
switch(opcode){
case 0x76 : std::cout<<"HALT "<<std::endl; opbytes = 1; break;
case 0x10 : std::cout<<"STOP $"<<(int)*(it+1)<<std::endl; opbytes =2; break;
//... About 250 different cases
default : std::cout<<"Instruction not implemented yet"<<std::endl;
}
return opbytes;
}
int main(){
std::vector<char> char_vect = {0x76, 0x10, 0x20}; // Fill vector of char
std::vector<char>::iterator it = char_vect.begin();
// First I only did that
//while (it!=char_vect.end()){
// it+=disassemble(it);
//}
// But I have to check that I do not go out of the char_vect
while (it!=char_vect.end()){
try{
it+=disassemble(it);
//check that it do not overpass end
if (size_t(it - char_vect.begin())>char_vect.size()){
throw "Try to disassemble instruction outside of memory bounds";
}
}
catch(const char * c){
std::cerr << "Fatal error: " << c << std::endl;
return 1;
}
}
return 1;
}
This code works fine. Now I wonder, I have a possible exception case which is the iterator going further than vect_char.end()
. Is a try / catch
an appropriate way to handle this case knowing that:
The reason for the iterator to go out of bounds could be either:
- A non valid input byte sequence, for example {0x76, 0x20, 0x10} since the instruction 0x10 expects an argument. This should not append.
- A mistake in the disassemble function. For exemple with the valid input {0x76, 0x10, 0x20}, if I code by mistake that 0x10 uses 3 opbytes instead of 2, the iterator will go out of bounds. This should not append either.
If I iterated through the
vect_char
with an index, I would not have this issue and the code would be more compact
I never really used try/catch before and I do not know if it is intented for such situations, so I would like to know, how would you have handled this unexpected case?
disassemble()
. \$\endgroup\$