boost::signals2::scoped_connection::~scoped_connection() can throw exception - boost

Our coding requirements state don't let exceptions leave the destructor body, but sometimes it's difficult to achieve. The current problem is that boost::signals2::connection::disconnect() function can throw an exception. For me that's strange because scoped_connection also calls 'disconnect()' in the destructor. So, is this a problem of the scoped_connection implementation, or there are some exceptions to the rule "exception must not to leave destructor body"?
BOOST_LIB_VERSION "1_68"
An example code snipet can look like this:
class Client
{
Client(Server& server)
{
m_connection = server.subscribe([this](const Event& event){ update(event); });
}
~Client() noexcept
{
m_connection.disconnect();
}
private:
void update(const Event& event);
boost::signals2::connection m_connection;
};

Related

How to print stacktrace once an exception is thrown before the catch block (stack unwinding)

Let's say we have the following code:
#include <exception>
void funcA() {
funcB();
}
void funcB() {
funcC();
}
void funcC() {
funcD();
}
void funcD() {
throw std::runtime_error("Exception!!"); //3
}
void funcE() {
int * p;
delete p; //4
}
int main (int argc, char **argv) {
try {
funcA(); //1
} catch (std::exception exc) {
std::cerr << exc.what() << endl; //2
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
I want to print the stack trace with the line number of the thrown exception in a multi-threaded efficient way.
I've been checking the last couple of days the solutions and approaches people are doing but unfortunately nothing was useful in my case. I can use for example the boost library boost::stacktrace::stacktrace() in //2 or any other library but the problem here is I have to catch the exception to do this and this approach is not efficient if your code has hundreds of nested functions. You can't just go over all of them and wrap each one with try-catch and handle them separately.
So basically what I need to do is if an exception is thrown at //3 I should be able to print the stack trace of the exception in `//2
I'm aware of the stack unwinding and how it works, but as far as I understand whenever your code reaches the catch block this means that the exception stack has been unwinded and you can't get it. Please correct me if I'm wrong!
Is there a way at least to add something similar to middleware before unwinding the exception stack? Or do I have to do it manually?
Edit:
Also, what would happen when I can funcE() is a memory access exception but this exception is never caught. Is there a way to catch such kind of exceptions or at least print its stack trace before the crash?
Note:
I'm running my code on Linux and macOS, C++11 with Silicon web framework.
It's a big system so I'm trying to achieve some logging mechanism that can be used across the system.
I'm posting this in case anyone came across the same question and wanted a quick useful answer.
I've ended up overriding the main C++ throw exception behavior using this gist
I've changed a few things in the __cxa_throw function to tackle my own issue and used boost::stacktrace to get a more human-readable stack trace.

Kotlin Coroutines remove exception handler from scope

In code below I am fetching some data. If error/exception was thrown I want the exception handler to catch it. Once done with fetching, I am posting the result using LiveData to whoever is observing.
What I am trying to achieve is that the exception handler to finish its job once I post the result. Which means, if the observer handling the result also throws an exception, I don't want the coroutine exception handler to catch it (Which is the case in code below).
fun loadPrerequisites(resultObserver: MutableLiveData<PrerequisiteDataHolder?>) {
val exceptionHandler = CoroutineExceptionHandler { _, throwable ->
resultObserver.postValue(null)
}
scope.launch(Dispatchers.IO + exceptionHandler) {
val deferredCreationScheme = async {
fetchCreationScheme()
}
val creationScheme = deferredCreationScheme.await()
//TODO remove exception handler at this stage?
resultObserver.postValue(PrerequisiteDataHolder(creationScheme))
}
}
Is there a way to remove the exception handler before posting the result to the LiveData? Or must I introduce a new scope?
You seem to have misunderstood the purpose of the coroutine exception handler. It is the coroutine equivalent of uncaughtExceptionExceptionHandler in Java and its purpose is to inform you of an exception that has already broken its coroutine. You seem to want to use it to implement business logic-level exception handling.
The coroutine exception handler is not a replacement for the try-catch block, and the latter is what you should use in your case.
I think you don't need async in your code in the first place, I believe this is all you really need:
scope.launch(Dispatchers.IO) {
resultObserver.postValue(
try {
PrerequisiteDataHolder(fetchCreationScheme())
} catch (e: Exception) {
null
}
)
}
I typically use a helper function for code like this:
inline fun <T> tryOrNull(block: () -> T) = try {
block()
} catch (t: Throwable) {
null
}
Then your code becomes
scope.launch(Dispatchers.IO) {
tryOrNull { PrerequisiteDataHolder(fetchCreationScheme()) }
.also { resultObserver.postValue(it) }
}

Exceptions w/QtConcurrent::Exception and boost::exception

I want to use an exception hierarchy where the base exception class derives from boost::exception so that I can get the nice and useful diagnostic information that that class has to offer and QtConcurrent::Exception so that I can throw my exceptions across threads.
Hence, my base exception class looks like:
class MyException : public QtConcurrent::Exception, public boost::exception
{
public:
MyException() { };
virtual ~MyException() throw() { }
// required by QtConcurrent::Exception to be implemented
virtual void raise() const { throw *this; }
virtual MyException* clone() const { return new MyException(*this); }
};
Per QtConcurrent::Exception's documentation, raise() and clone() must be implemented in any class derived from QtConcurrent::Exception. So, the rest of my code may look something like:
void foo()
{
BOOST_THROW_EXCEPTION(MyException());
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
try
{
foo();
}
catch (const MyException& me)
{
std::cerr << boost::diagnostic_information(me);
}
return 0;
}
However, using the BOOST_THROW_EXCEPTION() macro causes the following compilation error:
error C2555: 'boost::exception_detail::clone_impl::clone':
overriding virtual function return type differs and is not covariant
from 'MyException::clone'
I am not entirely sure what this error is telling me (my fault, not the errors, I'm sure!).
If I instead use throw MyException(); the code compiles just fine. As I mentioned above, I'd like to use BOOST_THROW_EXCEPTION() so that I get the diagnostic information in my exceptions.
I know that one possible work-around could be another class derived from just QtConcurrent::Exception that has a boost::exception member, essentially a container for the actual error. But if possible, I would like to continue to have the MyException class inherit from both QtConcurrent::Exception and boost::exception.
Can someone offer some insight into what the error is saying? Is there any way to accomplish what I want?

Should a method should be throwing an exception to the Unit Test?

I have a simple method for sending emails:
public void notifyEmail(string messageSubject, string messageBody)
{
MailMessage message = new MailMessage(from, to);
message.Subject = messageSubject;
message.Body = messageBody;
SmtpClient client = new SmtpClient(smtp_client);
client.Send(message);
message.Dispose();//release everything related
}
And a unit test (I'm learning):
[TestMethod()]
public void notifyEmailTest()
{
eMail target = new eMail("TEST Subject","TEST Body"); // TODO: Initialize to an appropriate value
bool testSent = true;
try
{
target.notifyEmail();
}
catch (Exception)
{
testSent = false;
}
Assert.IsTrue(testSent);
}
I deliberately set the smtp_client variable value to something invalid.
Running the code in my project results in an error.
Running the test method results in a Pass. Should my test or method be structured differently so that errors will fail the test?
I always do everything I can to avoid putting try-catch clauses on my unit tests. Instead try using the ExpectedException attribute (the attribute is the same for NUnit and MSTest) and set the type to the exception you are expecting i.e.
[TestMethod]
[ExpectedException(typeof(NetworkException))]
public void ShouldThrowNetworkExceptionIfSmtpServerIsInvalid)
{
//... test code here.
}
Another approach that I have used is to create a static class with an AssertExpectedException method since sometimes a method can throw the same type of exception for different reasons and the only way to know for sure if the accurate message is being returned is with custom code since the attribute does not assert the message the thrown exception is returning.
Hope this helps.
Regards.
If you expect that target.notifyEmail() should be throwing an exception, then that's what you should be testing for. If you were using NUnit you could use Assert.Throws<T>, e.g.
[Test]
public void notifyEmailTestFails()
{
// TODO: Initialize to an appropriate value
eMail target = new eMail("TEST Subject","TEST Body");
Assert.Throws<InvalidOperationException>(target.notifyEmail());
}
However, now I see you're using VSUnit you should be using [ExpectedException(typeof(...))]
as mentioned in other answers.
In general you should have separate tests for success, failure, and for exception conditions.
The way I normally do this is to decorate the test with ExpectedException (
http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.expectedexceptionattribute(v=vs.80).aspx)
. But you want to catch something MUCH less generic than "Exception."
If you don't want to use expected exception, then instead of:
bool testSent = true;
try
{
target.notifyEmail();
}
catch (Exception)
{
testSent = false;
}
Assert.IsTrue(testSent);
You can be a little less verbose:
try{
target.notifyEmail();
Assert.Fail("Expected an exception here");
}
catch (SmtpException){
}
I would highly recommend you to try the FluenAssertions:
http://fluentassertions.codeplex.com/
They are simple awesome and Elegant
And they let you check the exception message (You can not do that with the ExpectedException attribute)
Example:
using FluentAssertions;
[TestMethod]
public void notifyEmailTest()
{
eMail target = new eMail("TEST Subject","TEST Body"); // TODO: Initialize to an appropriate value
target.Invoking(x => x.notifyEmail())
.ShouldThrow<YourExcpectedException>()
.WithMessage("Your expected message", FluentAssertions.Assertions.ComparisonMode.Substring);
}

Getting an Unhandled Exception in VS2010 debugger even though the exception IS handled

I have an issue with VS2010 where the debugger stops with an Unhandled Exception. However, the exception is definitely handled. In fact, if I put code in the catch block, I'll hit it when I press F5. In Debug -> Exceptions, I definitely do not have the "Thrown" checkbox checked, so IMO there is absolutely no reason for the unhandled exception dialog to pop up...
I can't post the exact code, but will work on a sample soon. The basic idea behind the offending code section is that I have a thread that talks to hardware, and if I have an error talking to it, then I throw a HardwareException. The thread is launched with BeginInvoke, and the exception is caught in the callback handler when I call EndInvoke.
When the exception is thrown in the debugger, I get a messagebox that says 'HardwareException not handled by user code". But it is!!!
EDIT -- Well, this is driving me crazy. I've got sample code that is representative of the code I have in my application, and it looks like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Remoting.Messaging;
using System.Threading;
namespace ConsoleApplication1
{
public class HardwareException : ApplicationException
{
public HardwareException( string message) : base(message) {}
}
class Program
{
delegate void HardwareTestDelegate();
static void Main(string[] args)
{
HardwareTestDelegate d = new HardwareTestDelegate( HardwareTestThread);
d.BeginInvoke( HardwareTestComplete, null);
while( true);
}
static void HardwareTestThread()
{
throw new HardwareException( "this is a test");
}
static void HardwareTestComplete( IAsyncResult iar)
{
try {
AsyncResult ar = (AsyncResult)iar;
HardwareTestDelegate caller = (HardwareTestDelegate)ar.AsyncDelegate;
caller.EndInvoke( iar);
} catch( Exception ex) {
Console.WriteLine( "Should see this line without getting an unhandled exception message in the IDE");
}
}
}
}
I throw my HardwareException from the thread, and then handle the exception when EndInvoke is called. I guess Murphy was right, because when I run this sample code, it does what I expect -- i.e. no unhandled exception error message pops up in the IDE!
Here is the response from Microsoft, case 111053102422121. Allen Weng writes the following:
Analysis:
For your information, CLR will re-throw the exception inside the callback when you call EndInvoke(). Below is a simplified version of EndInvoke():
public object EndInvoke(IAsyncResult asyncResult)
{
using (new MultithreadSafeCallScope())
{
ThreadMethodEntry entry = asyncResult as ThreadMethodEntry;
............
if (entry.exception != null)
{
throw entry.exception;
}
}
}
The exception will be handled in the call back function or in the asynchronous method if an exception handler is provided. This is how it works without a debugger attached.
When you run it in VS.NET, the debugger seems checking only the presence of the exception handler in the asynchronous method. If there is no such handler, the debugger would think the exception is not handled and pop up an error message notifying you of this.
Suggestion:
The application should work as expected when you run it stand alone. If the error message is annoying in debugging for you, you can disable it by unchecking “User unhandled” for “Common Language Runtime Exceptions”in the Exception dialog box (Debug|Exceptions or press CTRL+ATL+E). Or you can add try/catch in the asynchronous method. In the latter case, the exception is set to null and won’t be re-thrown in EndInvoke().
I'm having this same problem, so I'll post this possible workaround for posterity's sake:
In your code that throws an exception into the .NET code (HardwareTestThread() in the example above,) catch the exception that's being thrown and wrap it in some esoteric .NET exception type for which you can disable the "user-unhandled" option in the Debug>Exceptions dialog. For my case, I needed to allow an IOException to propagate through some .NET code back to my code, so I just caught the IOException and wrapped in an AppDomainUnloadedException before letting it propagate through the .NET code back to my catch block. I chose AppDomainUnloadedException because user-unhandled is unchecked for it by default and it's in the System.dll assembly, so it was already being imported in my project, though any exception should work, so long as you disable the "user-unhandled" option for it and you don't care that the debugger won't break on that type of exception in the future.
Here's my code that wraps the IOException I was needing to propagate:
public override int Read(byte[] buffer, int offset, int count)
{
try { return innerStream.Read(buffer, offset, count); }
catch (IOException ex) { throw new AppDomainUnloadedException("Exception from innerStream: " + ex.Message, ex); }
}
And here's my code where I'm catching it on the other side of the .NET code it needed to propagate through:
try { bytesRead = sslStream.Read(buffer, offset, count); }
catch (Exception ex) { /* ex handled here. */ }

Resources