With Do Begin Statement in C++ Builder - c++

I wanna know how to write the following codes in C++ Builder by using With Do Begin statement similar to Delphi.
I tried with ComboBox->Text .... do ... try and it's not working. I tried with just do ComboBox->Text .... try, also not working.
if (ComboBox->Text.operator==(String("C++ Builder XE7")))
{
try
{
// do something
if ((Form1->Memo1->Lines->Text).Pos("<") !=0)
{
// do something
}
}
catch(Exception &ex)
{
ShowMessage(ex.ToString());
}
if (ComboBox->Text.operator==(String("C++ Builder XE8")))
{
try
{
// do something
if ((Form1->Memo1->Lines->Text).Pos("<") !=0)
{
// do something
}
}
catch(Exception &ex)
{
ShowMessage(ex.ToString());
}

There is no equivalent to Delphi's with statement in C++. The best you can do in C++ is use pointers/references instead, eg:
TComboBox *cb = ComboBox;
TStrings *lines = Form1->Memo1->Lines;
if (cb->Text == "C++ Builder XE7")
{
try
{
// do something
if (lines->Text.Pos("<") != 0)
{
// do something
}
}
catch(const Exception &ex)
{
ShowMessage(const_cast<Exception&>(ex).ToString());
}
}
if (cb->Text == "C++ Builder XE8")
{
try
{
// do something
if (lines->Text.Pos("<") != 0)
{
// do something
}
}
catch(const Exception &ex)
{
ShowMessage(const_cast<Exception&>(ex).ToString());
}
}

Related

Opencv4nodejs addon for cv::createLineSegmentDetector() function crashed. Exception can only be caught by catch(...). How to debug type of exception?

I am trying to make an integration of cv::LineSegmentDetector to opencv4nodejs which is an node addon of opencv (link: https://github.com/justadudewhohacks/opencv4nodejs). I have successfully complied an opencv4nodejs module which get loaded by require. Initially was facing problems of opencv_core.dll , and opencv_imgproc.dll while loading the opencv4nodejs.node module to js. But cv::createLineSegmentDetector() crashes catch( std::exception &e) does not work but catch(...) exception catches it. But its still does not work.
Here is the code.
#include <nan.h>
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include "macros.h"
class LineSegmentDetector : public Nan::ObjectWrap
{
public:
cv::Ptr<cv::LineSegmentDetector> m_plsd;
static NAN_MODULE_INIT(Init);
static NAN_METHOD(New);
static NAN_METHOD(Detect);
static Nan::Persistent<v8::FunctionTemplate> constructor;
};
Here is the CC file.
#include "LineSegmentDetector.h"
#include "Mat.h"
#include "Vec4.h"
Nan::Persistent<v8::FunctionTemplate> LineSegmentDetector::constructor;
// Nan::Persistent<v8::FunctionTemplate> Mat::constructor;
// Nan::Persistent<v8::FunctionTemplate> Vec4::constructor;
NAN_MODULE_INIT(LineSegmentDetector::Init)
{
v8::Local<v8::FunctionTemplate> ctor = Nan::New<v8::FunctionTemplate>(LineSegmentDetector::New);
constructor.Reset(ctor);
ctor->InstanceTemplate()->SetInternalFieldCount(1);
ctor->SetClassName(Nan::New("LineSegmentDetector").ToLocalChecked());
Nan::SetPrototypeMethod(ctor, "detect", LineSegmentDetector::Detect);
target->Set(Nan::New("LineSegmentDetector").ToLocalChecked(), ctor->GetFunction());
}
std::string handle_eptr(std::exception_ptr eptr) // passing by value is ok
{
try
{
if (eptr)
{
std::rethrow_exception(eptr);
}
}
catch (const std::exception &e)
{
return std::string("Caught exception \"") + e.what() + std::string("\"\n");
}
}
NAN_METHOD(LineSegmentDetector::New)
{
// throw an error if constructor is called without new keyword
if (!info.IsConstructCall())
{
return Nan::ThrowError(Nan::New("LineSegmentDetector::New - called without new keyword").ToLocalChecked());
}
LineSegmentDetector *self = new LineSegmentDetector();
if (self == nullptr)
{
return Nan::ThrowError(Nan::New("LineSegmentDetector::New - self was null").ToLocalChecked());
}
try
{
self->m_plsd = cv::createLineSegmentDetector();
}
catch (...)
{
// std::exception_ptr eptr = std::current_exception();
return Nan::ThrowError(Nan::New("LineSegmentDetector::New - cv::createLineSegmentDetector failed").ToLocalChecked());
}
self->Wrap(info.Holder());
// return the wrapped javascript instance
info.GetReturnValue().Set(info.Holder());
}
NAN_METHOD(LineSegmentDetector::Detect)
{
FF::TryCatch tryCatch("LineSegmentDetector::Detect");
cv::Mat gray;
if (Mat::Converter::arg(0, &gray, info))
{
return tryCatch.reThrow();
}
LineSegmentDetector *self = Nan::ObjectWrap::Unwrap<LineSegmentDetector>(info.This());
std::vector<cv::Vec4f> lines;
self->m_plsd->detect(gray, lines);
v8::Local<v8::Value> val = Vec4::ArrayWithCastConverter<cv::Vec4f>::wrap(lines);
info.GetReturnValue().Set(val);
}
As I understood there is no problem with my code the implementation is not present in version 3.4.
LineSegmentDetectorImpl::LineSegmentDetectorImpl(int _refine, double _scale, double _sigma_scale, double _quant,
double _ang_th, double _log_eps, double _density_th, int _n_bins)
{
CV_Assert(_scale > 0 && _sigma_scale > 0 && _quant >= 0 &&
_ang_th > 0 && _ang_th < 180 && _density_th >= 0 && _density_th < 1 &&
_n_bins > 0);
CV_UNUSED(_refine); CV_UNUSED(_log_eps);
CV_Error(Error::StsNotImplemented, "Implementation has been removed due original code license issues");
}

How to assert that an error message equals to certain char expression

I am trying to call a function from my Calculator class in a test class.
How do I assert that exception message thrown by Calculator equals to one I expect?
My calculator code:
void Calculator::add() {
if (_stack.empty()) {
throw std::runtime_error("empty stack");
}
else if (_stack.size() == 1) {
throw std::runtime_error("Wrong Value");
}
else if (_stack.size() > 2) {
throw std::runtime_error("Wrong Value");
}
else {
double res = this->pop() + this->pop();
this->push(res);
}
}
Here is my test class:
TEST_METHOD(should_throw_error_if_stack_is_empty) {
Assert::AreEqual([] {
Calculator* myCalculator = new Calculator();
try {
myCalculator->add();
}
catch (std::runtime_error const& ex)
{
return (ex.what());
}
}, "empty stack");
}
The reason it does not work: Value returned by lambda function has type const char* while my expression type is const char. How should I do it?
And is the approach I follow a good practice in general? I mean catching the exceptions thrown by class in a unit test?

C++ successful `try` branch

Let's consider some artificial C++ code:
int i = 0;
try { someAction(); }
catch(SomeException &e) { i = -1; }
i = 1;
... // code that uses i
I want this code to assign -1 to i in case of someAction() throws exception and assign 1 in case if there was no exception. As you can see now this code is wrong because i finally always becomes 1. Sure, we can make some trick workarounds like:
int i = 0;
bool throwed = false;
try { someAction(); }
catch(SomeException &e) { throwed = true; }
i = throwed ? -1 : 1;
... // code that uses i
My question is: is there anything in C++ like "successful try branch", where I do some actions in case if there were no any throws in try block?
Something like:
int i = 0;
try { someAction(); }
catch(SomeException &e) { i = -1; }
nocatch { i = 1; }
... // code that uses i
Surely, there is no nocatch in C++ but maybe there is some common beautiful workaround?
int i = 0;
try { someAction(); i = 1; }
catch(SomeException &e) { i = -1; }
Aside from the simple solution
try
{
someAction();
i = 1;
}
catch(SomeException &e)
{
i = -1;
}
you should consider what you are planning to do with the value of i further in the code - use it in if statements? That is poor design, you could simply put all the code inside the braces after try and catch respectively.

Error checking on many function calls

Sometimes when I am programming in C++/C I end up calling the same function multiple times and I was wondering what is the most efficient way to check for errors for all of those calls? Using if else statements take up a lot of code and look ugly. I have come up with my own way of checking for errors, perhaps there is a better way that I should use.
int errs[5] = {0};
errs[0] = functiona(...);
errs[1] = functiona(...);
...
errs[5] = functiona(...);
for (int i = 0; i < 5; i++)
{
if (err[i] == 0)
MAYDAY!_wehaveanerror();
}
Note: I understand that using try and catch might be better for C++ as it would solve this problem by throwing an exception on the first error, but the problem with that is that it is not compatible with a lot of functions that return error codes such as the Windows API. Thanks!
You could write some pseudo-C++ like this:
struct my_exception : public std::exception {
my_exception(int); /* ... */ };
int main()
{
try
{
int e;
if ((e = function()) != SUCCESS) { throw my_exception(e); }
if ((e = function()) != SUCCESS) { throw my_exception(e); }
if ((e = function()) != SUCCESS) { throw my_exception(e); }
}
catch (my_exception & e)
{
std::cerr << "Something went wrong: " << e.what() << "\n";
}
}
If...IF the function has a chance to throw a different error you should also add a catch all.
struct my_exception : public std::exception {
my_exception(int); /* ... */ };
int main()
{
try
{
int e;
if ((e = function()) != SUCCESS) { throw my_exception(e); }
if ((e = function()) != SUCCESS) { throw my_exception(e); }
if ((e = function()) != SUCCESS) { throw my_exception(e); }
}
catch (my_exception & e)
{
std::cerr << "Something went wrong: " << e.what() << "\n";
}
catch (...)
{
//Error Checking
}
}
What about handling the checking in a function?
void my_function() {
if (!create_window())
throw Error("Failed to create window");
}
int main() {
try {
my_function();
} catch (const Error& e) {
cout << e.msg << endl;
} catch (...) {
cout << "Unknown exception caught\n"
}
return 0;
}
If you're calling the same function over and over again, the most succinct way might be to use a macro. I would suggest something like:
#define CHECKERROR(x) if(x == 0) wehaveanerror()
CHECKERROR(function(...));
CHECKERROR(function(...));
Obviously, this macro would be very specific to the particular function and error handler involved, so it may be prudent to undef it after those calls.
Doing it more old-school, but keeping w/ the original error response but responding as soon as an error occurs w/o looking ugly:
#define callcheck(r) if ((r)==0) MAYDAY!_wehaveanerror()
callcheck(functiona(...));
callcheck(functiona(...));
...

Try-Catch Problem in c++

I am trying queue implementation in c++. During that I am having this problem.
void Queue::view()
{
int i;
try
{
if(Qstatus==EMPTY)
{
UnderFlowException ex = UnderFlowException("\nQUEUE IS EMPTY");
throw ex;
}
}
i=front;
cout<<"Queue contains...\n";
while(i <= rear)
{
cout<<queue[i]<<" ";
i++;
}
}
This gives an error as :
error: expected ‘catch’ before ‘i’
I think this problem is arises since I doesn't written catch block below try block.
But If want to write the catch block in main(), ( like in this case ), how could I do that?
Before, that Could I do that? If not Why?
catch block must follow the try block. If you want the catch to be in main - that's where the try has to be too. You can throw everywhere, doesn't have to be inside a try block within the same function.
It should be something like this:
void Queue::view()
{
int i;
if(Qstatus==EMPTY)
{
UnderFlowException ex = UnderFlowException("\nQUEUE IS EMPTY");
throw ex;
}
i=front;
cout<<"Queue contains...\n";
while(i <= rear)
cout<<queue[i]<<" ";
}
/// ...
int main()
{
Queue q;
try{
q.view();
}
catch(UnderFlowException ex)
{
/// handle
}
catch (...)
{
/// unexpected exceptions
}
// follow the success/handled errors
}
You simply need to remove the try block. A try block always goes with a catch.
void Queue::view()
{
int i;
if(Qstatus==EMPTY)
{
ex = UnderFlowException("\nQUEUE IS EMPTY");
throw ex;
}
i=front;
cout<<"Queue contains...\n";
while(i <= rear)
cout<<queue[i]<<" ";
}
You can then include a try/catch construct in your main.
int main()
{
Queue queue;
try
{
queue.View()
}
catch(UnderFlowException ex)
{
//handle ex
}
return 0;
}
All try blocks need at least one associated catch block. You should remove the try block if you have no intentions of handling any exceptions here. Exceptions can be (and usually should be!) thrown outside of a try block.
Make your code catch and rethrow the exception, like this:
try
{
if(Qstatus==EMPTY)
{
UnderFlowException ex = UnderFlowException("\nQUEUE IS EMPTY");
throw ex;
}
} catch( ... ) {
throw; // rethrow whatever exception we just catched
}
Although you don't even need the try block in the first place. Looks like just throw ex; would work, since you don't intend to catch it but just throw it.
try{
}
catch(Exception ex){
}
Catch must be immediately after try. These are the rules.