How do I catch this exception in Visual Studio 2015? - exception

I encountered this issue in my application. Hitting the debug button provided this detail:
Exception thrown: write access violation.
std::map<ATL::CStringT<wchar_t,StrTraitMFC<wchar_t,ATL::ChTraitsCRT<wchar_t> > >,bool [52],std::less<ATL::CStringT<wchar_t,StrTraitMFC<wchar_t,ATL::ChTraitsCRT<wchar_t> > > >,std::allocator<std::pair<ATL::CStringT<wchar_t,StrTraitMFC<wchar_t,ATL::ChTraitsCRT<wchar_t> > > const ,bool [52]> > >::operator[](...) was 0x111026CE50857E9.
If there is a handler for this exception, the program may be safely continued.
The code it fell over on was:
m_mapStudentAssignedStudyPoints[strName][iStudyPoint] = false;
The definition of that variable:
const int kMaxStudyPointCount = 52;
typedef map<CString, bool[kMaxStudyPointCount]> AssignedStudyPoints;
AssignedStudyPoints m_mapStudentAssignedStudyPoints;
I would love to give you a sample application but it is a huge application. It looked to me that it fell over on the [] assignment.
I did more investigation and iStudyPoint was set to 65535 (which I understand to be -1). My bool array is limited to 0-51 so I am not surprised it asserted.
I have now resolved the root cause of having 65535 in my code. But, my question, is what type of try/catch statement do I use so that I can catch this kind of issue when assigning my map entry content?

Related

Throw Exceptions in CODESYS

How can I throw standard system exceptions (and if possible, create custom exceptions and throw them too).
The simplest thing that comes to mind, is to just divide a variable by zero, but that's just a hack at best.
I did find mentions of a function AppGenerateException in the CmpApp library, but I can't find any documentation for it, nor any examples. Can anybody point me to some documentation for this?
Out of curiosity I checked the AppGenerateException and got it working. Got some help from this Codesys help page.
I still think this is not the best way to achieve what you need, but it could work.
Unfortunately, I have 64 bit system and the TRY..CATCH is not yet working in other that 32 bit systems as far as I know, so I couldn't test catching.
Add the following libraries:
CmpApp
SysExcept
Then the following code seems to work. Set ThrowErr to true to get the system exception.
PROGRAM PRG_TestThrow
VAR CONSTANT
MY_PRIVATE_EXCEPTION : DWORD := 32001;
END_VAR
VAR
ThrowErr : BOOL; //Set this to TRUE to throw an error
//The next two are for getting App instance
_pApp : POINTER TO CmpApp.APPLICATION;
_Result : SysExcept.SysTypes.RTS_IEC_RESULT;
END_VAR
//Get App instance
_pApp := AppGetCurrent(pResult := ADR(_Result));
IF ThrowErr THEN
ThrowErr := FALSE;
IF _pApp <> 0 THEN
//Throw divide by zero exception
AppGenerateException(pApp:=_pApp, ulException:=RtsExceptions.RTSEXCPT_DIVIDEBYZERO);
//You could use probably any available number as your own custom exception.
//For example the following works BUT not sure if it's ok to this.
//AppGenerateException(pApp:=_pApp, ulException:=MY_PRIVATE_EXCEPTION);
//See RtsExceptions type for available exception codes.
//For my Codesys version, it has largest exception number of 0x2000 so all larger number are free (for now...)
END_IF
END_IF
It seems that it's possibly to use any custom exception code like:
AppGenerateException(pApp:=_pApp, ulException:=MY_PRIVATE_EXCEPTION);
But it's not documented so I would be careful.

CPLEX running out of memory without exception

I'm running CPLEX through the COIN/OSI interface (OsiCpxSolverInterface). For some large LPs I get an error message CPX0000 CPLEX Error 1001: Out of memory.
Despite the error message, no exception (CoinError) is thrown. Looking at the source code of OsiCpxSolverInterface it looks like the return code of CPXlpopt must have been 0.
To be clear: my question is not how to avoid the out-of-memory problem. I'm just looking for a way to detect it from my program.
I found a hack that works for me. Setting an error handlers log level to 0 only allows error messages through. Overwriting the MessageHandler's print method then allows to react to the error. This workaround is definitely a hack. If anyone has any better suggestions, I'd be happy to accept a different answer.
class ErrorCatchingCoinMessageHandler: public CoinMessageHandler {
public:
ErrorCatchingCoinMessageHandler()
: CoinMessageHandler() {
// Would be nice to also overwrite setLogLevel to avoid later changes
// but its not virtual
setLogLevel(0);
}
virtual int print() __attribute__((noreturn)) {
CoinMessageHandler::print();
abort(); // or throw a CoinError
}
};
// Use it like this
lp_solver->passInMessageHandler(new ErrorCatchingCoinMessageHandler());

Throw extra exception to avoid code duplication

First of all, I know the standard answer will be that exceptions are never to be used for flow control. While I perfectly agree with this, I've been thinking a long time about something I sometimes did, which I'll describe with the following pseudo-code:
try
string keyboardInput = read()
int number = int.parse(keyboardInput)
//the conversion succeeds
if(number >= 1000)
//That's not what I asked for. The message to display to the user
//is already in the catch-block below.
throw new NumberFormatException() //well, there IS something wrong with the number...
catch(NumberFormatException ex) //the user entered text
print("Please enter a valid number below 1000.")
First of all, take this example in a very abstract way. This does not necessarily have to happen. The situation simply is:
A user input needs to be constrained and can go wrong in 2 ways,
either
by a thrown exception the language defines, or by a check. Both errors
are reported by the user in the same way, because they do not need to know
the technical difference of what caused it.
I have thought of several ways to solve it. To begin with, it would be better to throw a custom made exception. The problem I then face is, if I catch it locally, what to do with the other exception? In se, the custom exception would be cause for a second catch-block, in which the message would be copied into just as well. My solution:
//number is wrong
throw new MyException()
catch(NumberFormatException ex)
throw new MyException()
catch(MyException ex) {
print("Please enter...")
The meaning of the exceptions' names is everything here. This application of custom-made exceptions is widely accepted, but essentially I didn't do anything different from the first way: I forced to go into a catch-block, albeit by throwing a custom exception rather than a standard-library one.
The same way applied to throwing the exception on to the calling method (thus not having a catch block for the custom exception) seems to make more sense. My method can go wrong in what is technically two ways, but essentially one way: wrong user input. Therefore, one would write a UserInputException and make the method throw this. New problem: what if this is the main method of an application?
I'm not currently struggling with a specific application to implement this kind of behaviour, my question is purely theoretical and non-language specific.
What is the best way to approach this?
I would consider the first exception to be low-level, and I would handle it (by translation in this case) at the point of call. I find that this leads to code that is easier to maintain and refactor later, as you have less types of exceptions to handle.
try
string keyboardInput = read()
try
int number = int.parse(keyboardInput)
catch(NumberFormatException ex)
throw MyException("Input value was not a number")
//the conversion succeeds
if(number >= 1000)
throw MyException("Input value was out of range")
catch(MyException ex) //the user entered text
print( ex.ToString() )
print("Please enter a valid number below 1000.")
I think you have essentially a few ways to go about it with minimal code duplication in mind:
Use a boolean variable/store the exception: If there was an error anywhere in the the general logic of the specific task you are performing, you exit on the first sign of error and handle that in a separate error handling branch.
Advantages: only one place to handle the error; you can use any custom exception/error condition you like.
Disadvantages: the logic of what you are trying to achieve might be hard to discover.
Create a general function that you can use to inform the user about the error (pre-calculating/storing all information that describes the general error, e.g. the message to display the user), so you can just make one function call when an error condition happens.
Advantages: the logic of your intent might be clearer for readers of the code; you can use anu custom exception/error conditon you like.
Disadvantages: the error will have to be handled in separate places (although with the pre-computed/stored values, there is not much copy-paste, however complex the informing the user part).
If the intent is clear, I don't think throwing exceptions from within your try block explicitly is a bad idea. If you do not want to throw one of the system provided exceptions, you can always create your own that derives from one of them, so you only need a minimal number (preferably one) of catch blocks.
Advantages: only one place to handle error condition -- if there is essentially only one type of exception thrown in try-block.
Disadvantages: if more than one type of exception is thrown, you need nested try-catch blocks (to propagate the exceptions to the most outward one) or a very general (e.g. Exception) catch block to avoid having to duplicate error reporting.
The way I see it is this:
Assuming there's no other way to parse your int that doesn't throw an exception, your code as it is now, is correct and elegant.
The only issue would be if your code was in some kind of loop, in which case you might worry about the overhead of throwing and catching unnecessary exceptions. In that case, you will have to compromise some of your code's beauty in favor of only handling exceptions whenever necessary.
error=false;
try {
string keyboardInput = read();
int number = int.parse(keyboardInput);
//the conversion succeeds
if(number >= 1000) {
//That's not what I asked for. The message to display to the user
//is already in the catch-block below.
error=true;
} catch(NumberFormatException ex) { //the user entered text
error=true;
}
if (error)
print("Please enter a valid number below 1000.");
Also you can think about why you're trying to aggregate two errors into one.
Instead you could inform the user as to what error they did, which might be more helpful in some cases:
try {
string keyboardInput = read();
int number = int.parse(keyboardInput);
//the conversion succeeds
if(number >= 1000) {
//That's not what I asked for. The message to display to the user
//is already in the catch-block below.
print("Please enter a number below 1000.");
} catch(NumberFormatException ex) { //the user entered text
print("Please enter a valid number.");
}
You do not need any exceptions in this particular example.
int number;
if (int.TryParse(keyboardInput, out number) && number < 1000) // success
else // error
However, the situation you describe is common in business software, and throwing an exception to reach a uniform handler is quite common.
One such pattern is XML validation followed by XSLT. In some systems, invalid XML is handled through catching validation exceptions. In these systems, it is pretty natural to reuse the existing exception handling in XSLT (which can naturally detect some classes of data errors that a particular validation language cannot):
<xsl:if test="#required = 'yes' and #prohibited = 'yes'>
<xsl:message terminate='yes'>Error message</xsl:message>
</xsl:if>
It is important to see that if such conditions are extremely rare (expected to occur only during early integration testing, and disappear as defects in other modules get fixed), most of the typical concerns around not using exceptions for flow control do not really apply.
What about approaching this validation problem by writing several validator classes that take in an input and return errors, or no errors. As far as your struggle with exceptions: put that logic into each validator and deal with it there on a case by case basis.
after that you figure out the correct validators to use for your input, collect their errors and handle them.
the benefits of this are:
Validators do one thing, validate a single case
Its up to the validation function to decide how to handle the errors. Do you break on first validation error or do you collect them all and then deal with them?
You can write your code is such a way that the main validation function can validate different types of input using the same code, just picking the correct validators using your favorite technique.
and disadvantages:
You will end up writing more code (but if you are using java, this should be put into the 'benefits' bucket)
here is some example pseudo-code:
validate(input):
validators = Validator.for(input.type)
errors = []
for validator in validators:
errors.push(validator.validate(input))
if errors:
throw PoopException
and some validators:
MaxValidator extends IntValidator:
validate(input):
errors = []
errors.push(super.validate(input))
if input > 1000:
errors.push("bleee!!!! to big!")
return errors
IntValidator:
validate(input):
try:
int.parse(input)
catch NumberFormatException:
return ['not an int']
return []
of course you would need to do some trickery to make the parent validator possibly return you a valid version of the input, in this case string "123" converted to an int so the max validator can handle it, but this can be easily accomplished by making the validators statefull or some other magic.
I can't see this answer anywhere in here, so I'll just post it as another point of view.
As we all know, you can actually break the rules if you know them well enough, so you can use throwing an Exception for flow control if you know it's the best solution for your situation. From what I've seen, it happens usually with some dumb frameworks...
That said, before Java 7 (which brought us the mighty multicatch construct), this was my approach to avoid code repetition:
try {
someOffendingMethod();
} catch (Exception e) {
if (e instanceof NumberFormatException || e instanceof MyException) {
System.out.println("Please enter a valid number.");
}
}
It's a valid technique in C#, too.

microchip exception handling

While running my program on a microchip ICD3 device, the exception handling looks weird. The program will stop response while exception occurs. While checking the code, I noticed that the default-general-exception-handler.c will create an infinite loop. It is really confusing because I cannot know where the error occurs and what is the reason. Does that mean Microchip doesn't support exception handling? Or is there a way to read the error message?
infinite loop:
--- \home\c11067\work\C32\builds\pic32-microchip-release-1.12-20101221-rc2-20101221\pic32-libs\libc\stubs\default-general-exception-handler.c
9D00DD28 1000FFFF beq zero,zero,0x9d00dd28
9D00DD2C 00000000 nop
By defining a _general_exception_handler, it works!
// declared static in case exception condition would prevent
// auto variable being created
static enum {
EXCEP_IRQ = 0, // interrupt
EXCEP_AdEL = 4, // address error exception (load or ifetch)
EXCEP_AdES, // address error exception (store)
EXCEP_IBE, // bus error (ifetch)
EXCEP_DBE, // bus error (load/store)
EXCEP_Sys, // syscall
EXCEP_Bp, // breakpoint
EXCEP_RI, // reserved instruction
EXCEP_CpU, // coprocessor unusable
EXCEP_Overflow, // arithmetic overflow
EXCEP_Trap, // trap (possible divide by zero)
EXCEP_IS1 = 16, // implementation specfic 1
EXCEP_CEU, // CorExtend Unuseable
EXCEP_C2E // coprocessor 2
} _excep_code;
static unsigned int _epc_code;
static unsigned int _excep_addr;
// this function overrides the normal _weak_ generic handler
void _general_exception_handler(void)
{
asm volatile("mfc0 %0,$13" : "=r" (_excep_code));
asm volatile("mfc0 %0,$14" : "=r" (_excep_addr));
_excep_code = (_excep_code & 0x0000007C) >> 2;
while (1) {
// Examine _excep_code to identify the type of exception
// Examine _excep_addr to find the address that caused the exception
}
}
On most microcontrollers, there isn't any code beyond what you put there. In most cases, if an exception occurs and you haven't defined a handler for it, the processor would have no idea how to put up a "Sorry, a system error occurred" dialog box. Using two bytes for a "branch-to-self" instruction is enough to yield a predictable response to an exception; without particular knowledge of any better course of action, a branch-to-self or forced reset is probably as good a response as anything.
PS--Some compilers for various platforms will omit vectors for unused interrupts or exceptions; if such exceptions occur unexpectedly, weird and bizarre things can happen. Some compilers will produce code that will force an immediate reset (note that if watchdog timer is enabled, a jump-to-self will cause a reset, eventually). Some compilers generate an immediate return-from-interrupt (which on some CPU's may be useless, and on others can cause bad behavior). My favorite pattern would be to have all unused interrupts make a call (not a branch) to an UnexpectedInterrupt label, which in the absence of any explicit definition will point to a branch-to-self instruction. If one does that, an UnexpectedInterrupt handler can pop the stack and record what type of unexpected interrupt occurred. I've not seen such a pattern, though, outside my own manually-generated interrupt vector tables.
Just as a heads-up for further PIC32 exception debugging, the exception codes and all the bits in the 'CAUSE' register (the value you're reading into your _excep_code variable before and-ing all the other bits away) are defined in:
PIC32 Family Reference Manual, Section 2.12.9 CAUSE Register
http://ww1.microchip.com/downloads/en/DeviceDoc/61113C.pdf

Handle access violation exception in C++ Builder?

I'm trying to do:
try{
int * i = NULL;
*i = 3;
}catch(Exception &Err){
ShowMessage(Err.Message);
}
I though that this should catch access violation exception and handle it by displaying an error message.
But for some reason I get simple
Access Violation
message instead of full one
Access Violation XXX in module YYY. Writing at address ZZZ.
BTW, ExceptObject() routine returns NULL for some strange reason.
What am I missing here?
In BCB5, catching an EAccessViolation works, e.g.:
#define AV_TRY { try {
#define AV_CATCH } catch(EAccessViolation &av) {Application->MessageBox((("Access Violation caught: " + string(__FILE__) + "; " + string(__FUNC__) + "; " + IntToString(__LINE__) + "\n\n") + av.Message.c_str()).c_str(), ("Program Error in " + string(class_name.c_str())).c_str(), MB_OK);} }
Note that class_name is specific to this project and should probably be replaced by AnsiString(this->ClassName) or left out. Also I've switched this code from logging silently to a database, to showing a MessageBox. I just wrap code where I've observed AVs in an AV_TRY ... AV_CATCH.
See the MSDN blog entry on Mixing SEH and C++ Exceptions. These are two different types of exceptions. Trying to catch a structured exception, generated by the OS, as a C++ exception isn't the correct way out of the box.
Temper this bit with this posting on not doing that.
Catching access violations can be a nice goal -- but something you may want to do within the context of debugging only. Catching access violations (or other major exceptions) in production code and trying to handle them is seldom going to result in correct operation.
Standard C++ does not specify that dereferencing a NULL pointer throws an exception - it says it results in undefined behaviour. On Windows platforms, the water is muddied somewhat by Windows Structured Exception Handling. This has nothing to do with C++ exception handling, except that some C++ run-times may translate these excptions into C++ exceptions. However, code that depends on such translations is not portable.
try {
int * i = NULL;
*i = 3;
}
catch (...) {
// This would catch the access violation but you don't have any more
// information of what has gone wrong
}
You can however, use structured exception handling (SEH) to catch all C++ exceptions. Since C++ exceptions are just a class based implementation based on SEH.