How to use try-catch syntax in Android JNI? - java-native-interface

How can I catch error in JNI ?
I am trying to convert std::string to jstring and return the value to java Code.
I am looking for a way where i can catch error thrown by "NewStringUTF" .
Please help!
jstring result;
try
{
result=env->NewStringUTF(data.c_str());
}
catch (std::exception e)
{
result=env->NewStringUTF("");
}
return result;
Her is my gradle
defaultConfig {
...
externalNativeBuild {
cmake {
cppFlags "-frtti -fexceptions"
}
}
}

If you want to coerce JNI exceptions to C++ exceptions you could do the following:
struct JNICheck {
JNIEnv * env;
JNICheck(JNIEnv * env) : env(env) {}
~JNICheck() {
jthrowable t = env->ExceptionOccured();
if (t) {
env->ExceptionClear();
throw t;
}
}
};
Now you can replace some uses of env with JNICheck(env) if you want them to generate exceptions:
try {
return JNICheck(env)->NewStringUTF(data.c_str());
} catch (jthrowable t) {
return env->NewStringUTF("");
}
The alternative is to subclass JNIEnv and override all methods with similar code.

Related

Correctly catching the CDatabase::Close exception

I thought I would do a little digging about cataching exceptions.
According to this question (C++ catching all exceptions) one of the answers states:
[catch(...)] will catch all C++ exceptions, but it should be considered bad design.
At the moment I have used this approach:
CPTSDatabase::~CPTSDatabase()
{
try
{
CloseDatabase();
}
catch(...)
{
}
}
void CPTSDatabase::CloseDatabase()
{
if (m_dbDatabase.IsOpen())
m_dbDatabase.Close();
}
I thought that this was the correct way because when I trace into CDatabase::Close() it does something similar:
// Disconnect connection
void CDatabase::Close()
{
ASSERT_VALID(this);
// Close any open recordsets
AfxLockGlobals(CRIT_ODBC);
TRY
{
while (!m_listRecordsets.IsEmpty())
{
CRecordset* pSet = (CRecordset*)m_listRecordsets.GetHead();
pSet->Close(); // will implicitly remove from list
pSet->m_pDatabase = NULL;
}
}
CATCH_ALL(e)
{
AfxUnlockGlobals(CRIT_ODBC);
THROW_LAST();
}
END_CATCH_ALL
AfxUnlockGlobals(CRIT_ODBC);
if (m_hdbc != SQL_NULL_HDBC)
{
RETCODE nRetCode;
AFX_SQL_SYNC(::SQLDisconnect(m_hdbc));
AFX_SQL_SYNC(::SQLFreeConnect(m_hdbc));
m_hdbc = SQL_NULL_HDBC;
_AFX_DB_STATE* pDbState = _afxDbState;
AfxLockGlobals(CRIT_ODBC);
ASSERT(pDbState->m_nAllocatedConnections != 0);
pDbState->m_nAllocatedConnections--;
AfxUnlockGlobals(CRIT_ODBC);
}
}
And the CDatabase::Close documentation does not even state anything about exceptions being thrown.
The linked answer does state:
You can use c++11's new current_exception mechanism.
It is not clear if we can use this approach given the CDatabase class we are using.
Since CDatabase::Close() is using THROW_LAST to throw CDBException, you have to use catch (CDBException* e). Even if you are not handling it, you still have to Delete the error. You might as well do this when CDatabase methods are called directly:
void CPTSDatabase::CloseDatabase()
{
try
{
if (m_dbDatabase.IsOpen())
m_dbDatabase.Close();
}
catch (CDBException* e)
{
//TRACE(L"DB error: " + e->m_strError);
e->Delete();
}
}
Or use
CPTSDatabase::~CPTSDatabase()
{
try { CloseDatabase(); }
catch (CDBException* e) { e->Delete(); }
catch(...) {}
}
Because in this code it's not clear where the exceptions are coming from. catch(...) {} will deal with other exceptions. In general catch(...) {} is not recommended because it doesn't give useful information, it just says "something went wrong..."
Use Standard Library exceptions only if you are adding throw in your own code, or when using std functions. Example:
try { std::stoi("wrong argument"); }
catch (const std::exception& e) { TRACE("%s\n", e.what()); }
try { throw 123; }
catch (int i) { TRACE("%d\n", i); }

print error while null value for SQL safety

How can I print "Error" while the JTextfield is empty
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
String sn =jX1.getText();
if (sn==null){
System.out.println("Error");
System.out.println("T");
}
Thanks
Try using a fail-safe method. Also Expanding on the comments, you should be logging data, in a better format. Java hosts a huge array of different way to log certain data. look here
As for your error handling, try-catch-finally. This isn't tested code. Let me know if you run into any issues, documentation on try-catch and other statements here or here
public static void main(String[] args) {
while (String sn == null)
try {
String sn = JX1.getText();
} catch (Exception ex) {
System.out.println("Exception thrown!");
} finally {
if (sn != null) {
System.out.println("Closing PrintWriter");
sn.close();
} else {
System.out.println("PrintWriter not open");
}
}

Exceptions and BDD in C++ - Catch library

I've been using Boost.Test so far but am now looking into using BDD with Catch instead, but I have some trouble figuring out a nice way of handling exceptions. Say I've got a test like this:
SCENARIO("connection handling", "[network]") {
boost::asio::io_service io;
GIVEN("a connection that should fail") {
connection::ptr conn = connection::create(new fake_provider<connection_refused>(io));
WHEN("trying to connect") {
conn->connect("localhost", 1);
THEN("connection was refused") {
some stuff to verify exception code
REQUIRE(conn->connected() == false);
}
}
}
}
Now I'm wondering how to handle the fact that connect() will throw an exception in a nice way. I figure I could save and store the exception in a try-catch and verify under THEN, but that doesn't seem very nice. In my Boost.Test testcases I did this:
bool error_is_connection_refused(boost::system::system_error ex) {
return ex.code() == boost::system::errc::connection_refused;
}
BOOST_AUTO_TEST_CASE(connect)
{
connection::ptr conn_refuse = connection::create(new fake_provider<connection_refused>(*io_ptr));
BOOST_REQUIRE_EXCEPTION(conn_refuse->connect("localhost", 1),
boost::system::system_error,
error_is_connection_refused);
BOOST_REQUIRE_EQUAL(conn_refuse->connected(), false);
}
But that doesn't seem very BDD. How do people usually handle exception throwing code when using BDD testing?
I'm a bit late to this as I've only just noticed the catch-unit-test tag :-)
Currently you can do:
REQUIRE_THROWS( <expr> );
or to test for a specific exception type:
REQUIRE_THROWS_AS( <type>, <expr> );
If you want to verify the contents of the exception message... there's not currently a way to do that without catching it yourself. That's a feature I've considered adding, though.
This is how to verify exception content as suggested by philsquared
#include <stdexcept>
#include "catch.hpp"
void my_func(double v)
{
// ...
}
TEST_CASE("wrong params", "[tag]") {
SECTION("wrong rate") {
try {
my_func(1.1); // must be in range [0..1]
REQUIRE_FALSE("must raise issue about rate");
}
catch(const std::invalid_argument& e) {
std::string str (e.what());
std::string str2 ("rate");
REQUIRE_FALSE(str.find(str2) == std::string::npos);
}
}
}

C++: check if a certain exception type was thrown without external libraries

I am writing up some tests for a C++ program and I would like to check that my program throws certain types of exceptions when given certain inputs. I have seen that this is doable using external libraries such as googletest, but I would like to know how this was implemented.
I would like to separate the test data from the test code as much as possible. In particular, I would like something like this:
void RunTests(InputList inputs) {
for (int i = 0; i < inputs.length; i++) {
if (FunctionIAmTesting(inputs[i].value) has the expected exception behavior) {
// Pass
} else {
// Fail
}
}
}
InputList inputs = InputList({
Input(5), // no exception when 5 is an input
Input<MyExceptionClass>(0), // MyExceptionClass thrown when 0 is an input
Input<MyOtherExceptionClass>(-1) // MyOtherExceptionClass thrown when -1 is an input
});
RunTests(inputs);
If you know what the type of exception you are looking for then you can target an exception of that type in the catch () statement.
try {
// Test code.
// Unexpected success
std::cerr << "Expected a RelevantException to be thrown." << std::endl;
}
catch (RelevantException& e)
{
// Expected exception, continue.
}
catch (...) // Catch all
{
// Unexpected exception
std::cerr << "Unexpected exception encountered, expected "
"RelevantException." << std::endl;
}
A several years back I wrote some simple library for "mocking" objects. And my goal was to check everything related to function calls. In the tests I wrote something like that:
MyMockedObject my;
mock::expect(my, "foo").in(10).out(20).returns(30);
mock::expect(my, "bar").throws(logic_error("bar failed"));
int v;
// test that my::baz() invokes my.foo(10, v)
// then my.bar which fails with the exception
my.baz();
Your task seems to be a little bit easier. All that you need is a way how to describe your expectations and some hack in the test runner to verify them at the end of a test (accordingly to the input). Your expectations are exceptions, just construct them somehow and associate with the input. In your example you did a half part of your work.
typedef std::map<Input, Exception> Expectations;
typedef std::pair<Input, Exception> Expectation;
// somewhere before the tests
expectations.insert(make_pair(Input(5)), NoThrowAnything);
expectations.insert(make_pair(Input(0)), MyException("some message"));
expectations.insert(make_pair(Input(-1)), MyOtherException("another message"));
void run_test(const Expectation& expect)
{
try {
// run the real test here based on Input (expect.first)
check_expectation(expect);
} catch (const Exception& ex) {
check_expectation(expect, ex);
}
}
void run_all_tests(const Expectations& expects)
{
for (e : expects) {
try {
run_test(e);
} catch (const ExpectationException ex) {
// failed expectation
}
}
}
void check_expectation(const Expectation& expect)
{
if (expect.second != NoThrowAnything) {
throw ExpectationFailure(expect);
}
}
void check_expectation(const Expectation& expect, const Exception& ex)
{
if (expect.second != ex) {
throw ExpectationMismatch(expect, ex);
}
}

Print an EObject?

I am writing some eclipse emf code and would like to print the content of an EObject (not store it to disk).
Here is what I try:
public static void print(EObject obj) {
Resource eResource = obj.eResource();
try {
eResource.save(System.out, null);
} catch (IOException e) {
e.printStackTrace();
}
}
but that gives a NullPointerException. I have tried this instead:
public static void print(EObject obj) {
ResourceSet resourceSet = new ResourceSetImpl();
resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap()
.put("*", new XMIResourceFactoryImpl());
Resource resource = resourceSet.createResource(URI.createURI("dummyfile.xml"));
resource.getContents().add(obj);
try {
resource.save(System.out, null);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
This works, but is it not possible to print to screen without specifying a dummy URI??
Updated to include EcoreUtil.copy()
Check this code.
Resource res = new XMLResourceImpl ();
res.getContents().add(EcoreUtil.copy(obj));
try {
resource.save(System.out, null);
} catch (IOException ioe) {
ioe.printStackTrace();
}
If that fails then yes you need a dummy URI
Resource res = new XMLResourceImpl (URI.createURI("dummyfile.xml"));
res.getContents().add(EcoreUtil.copy(obj));
try {
resource.save(System.out, null);
} catch (IOException ioe) {
ioe.printStackTrace();
}
Hm when I pass a copy:
Resource res = new XMLResourceImpl ();
res.getContents().add(ECoreUtil.copy(obj));
try {
resource.save(System.out, null);
} catch (IOException ioe) {
ioe.printStackTrace();
}
some of the xmi attributes are not printed. But if I call the above method multiple times and DON't pass a copy I get a NullPointerException. I guess I am not understanding some basic EMF/Containment functionality here?
So my updated question is:
Is it possible to print a FULL EObject model without modifying the content if the model is used in the following code?