diff --git a/lib/mqtt/client.rb b/lib/mqtt/client.rb
index <HASH>..<HASH> 100644
--- a/lib/mqtt/client.rb
+++ b/lib/mqtt/client.rb
@@ -287,8 +287,11 @@ class MQTT::Client
 
     # If a block is given, then yield and disconnect
     if block_given?
-      yield(self)
-      disconnect
+      begin
+        yield(self)
+      ensure
+        disconnect
+      end
     end
   end
 
diff --git a/spec/mqtt_client_spec.rb b/spec/mqtt_client_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/mqtt_client_spec.rb
+++ b/spec/mqtt_client_spec.rb
@@ -282,9 +282,19 @@ describe MQTT::Client do
       )
     end
 
-    it "should disconnect after connecting, if a block is given" do
-      expect(client).to receive(:disconnect).once
-      client.connect('myclient') { nil }
+    context "if a block is given" do
+      it "should disconnect after connecting" do
+        expect(client).to receive(:disconnect).once
+        client.connect('myclient') { nil }
+      end
+
+      it "should disconnect even if the block raises an exception" do
+        expect(client).to receive(:disconnect).once
+        begin
+          client.connect('myclient') { raise StandardError }
+        rescue StandardError
+        end
+      end
     end
 
     it "should not disconnect after connecting, if no block is given" do
put "disconnect" inside an "ensure" block

Also includes a spec for this behavior. This will cause the
client to disconnect even in cases where the connect block
raises an exception.