Просмотр исходного кода

2008-04-27 Tatsuhiro Tsujikawa <tujikawa at rednoah dot com>

	Rewritten Exception class. Throw exception object, not its pointer and
	catch by reference, so that remove problematic delete operator for
	catched exception.
	* src/Exception.cc
	* src/Exception.h
	* test/ExceptionTest.cc
	* src/*: All files throwing/catching exception.
	* test/*: All files throwing/catching exception.
Tatsuhiro Tsujikawa 17 лет назад
Родитель
Сommit
1ef99931e1
100 измененных файлов с 627 добавлено и 452 удалено
  1. 11 0
      ChangeLog
  2. 12 15
      src/AbstractCommand.cc
  3. 1 1
      src/AbstractCommand.h
  4. 12 8
      src/AbstractDiskWriter.cc
  5. 1 1
      src/AbstractProxyResponseCommand.cc
  6. 8 4
      src/BtAllowedFastMessage.cc
  7. 5 2
      src/BtBitfieldMessage.cc
  8. 5 2
      src/BtCancelMessage.cc
  9. 5 2
      src/BtChokeMessage.cc
  10. 1 2
      src/BtDependency.cc
  11. 5 2
      src/BtExtendedMessage.cc
  12. 10 7
      src/BtHandshakeMessageValidator.h
  13. 8 4
      src/BtHaveAllMessage.cc
  14. 5 2
      src/BtHaveMessage.cc
  15. 8 4
      src/BtHaveNoneMessage.cc
  16. 5 2
      src/BtInterestedMessage.cc
  17. 5 2
      src/BtNotInterestedMessage.cc
  18. 7 4
      src/BtPieceMessage.cc
  19. 5 2
      src/BtPortMessage.cc
  20. 1 1
      src/BtPostDownloadHandler.cc
  21. 9 5
      src/BtRejectMessage.cc
  22. 5 2
      src/BtRequestMessage.cc
  23. 5 2
      src/BtSuggestPieceMessage.cc
  24. 5 2
      src/BtUnchokeMessage.cc
  25. 1 1
      src/CheckIntegrityCommand.cc
  26. 1 1
      src/CheckIntegrityCommand.h
  27. 5 3
      src/ChunkedEncoding.cc
  28. 1 2
      src/CookieBoxFactory.cc
  29. 6 4
      src/DHTAnnouncePeerMessage.cc
  30. 1 2
      src/DHTAutoSaveCommand.cc
  31. 1 2
      src/DHTConnectionImpl.cc
  32. 7 7
      src/DHTEntryPointNameResolveCommand.cc
  33. 1 2
      src/DHTInteractionCommand.cc
  34. 2 2
      src/DHTMessageDispatcherImpl.cc
  35. 29 18
      src/DHTMessageFactoryImpl.cc
  36. 1 2
      src/DHTMessageReceiver.cc
  37. 4 3
      src/DHTMessageTracker.cc
  38. 1 2
      src/DHTPeerAnnounceCommand.cc
  39. 7 4
      src/DHTRoutingTableDeserializer.cc
  40. 4 2
      src/DHTRoutingTableSerializer.cc
  41. 3 5
      src/DHTSetup.cc
  42. 4 2
      src/DHTTokenTracker.cc
  43. 1 2
      src/DHTTokenUpdateCommand.cc
  44. 5 3
      src/DefaultBtAnnounce.cc
  45. 24 13
      src/DefaultBtContext.cc
  46. 6 3
      src/DefaultBtInteractive.cc
  47. 3 2
      src/DefaultBtMessageFactory.cc
  48. 33 23
      src/DefaultBtProgressInfoFile.cc
  49. 7 3
      src/DefaultExtensionMessageFactory.cc
  50. 2 1
      src/DefaultPieceStorage.cc
  51. 2 1
      src/DiskAdaptor.cc
  52. 11 16
      src/DlAbortEx.h
  53. 11 16
      src/DlRetryEx.h
  54. 8 6
      src/DownloadCommand.cc
  55. 11 16
      src/DownloadFailureException.h
  56. 27 6
      src/Exception.cc
  57. 14 18
      src/Exception.h
  58. 4 4
      src/ExpatMetalinkProcessor.cc
  59. 11 16
      src/FatalException.h
  60. 1 1
      src/FileAllocationCommand.cc
  61. 1 1
      src/FileAllocationCommand.h
  62. 1 2
      src/FileMetalinkParserState.cc
  63. 1 2
      src/FillRequestGroupCommand.cc
  64. 3 3
      src/FtpConnection.cc
  65. 1 1
      src/FtpInitiateConnectionCommand.cc
  66. 16 13
      src/FtpNegotiationCommand.cc
  67. 5 3
      src/HandshakeExtensionMessage.cc
  68. 1 1
      src/HelpItemFactory.cc
  69. 2 2
      src/HttpConnection.cc
  70. 2 2
      src/HttpHeaderProcessor.cc
  71. 1 1
      src/HttpInitiateConnectionCommand.cc
  72. 17 11
      src/HttpResponse.cc
  73. 8 5
      src/HttpResponseCommand.cc
  74. 4 1
      src/InitiateConnectionCommandFactory.cc
  75. 1 1
      src/InitiatorMSEHandshakeCommand.cc
  76. 1 1
      src/InitiatorMSEHandshakeCommand.h
  77. 5 4
      src/IteratableChunkChecksumValidator.cc
  78. 4 2
      src/LibgcryptARC4Context.h
  79. 4 2
      src/LibgcryptARC4Decryptor.h
  80. 4 2
      src/LibgcryptARC4Encryptor.h
  81. 10 6
      src/LibgcryptDHKeyExchange.h
  82. 4 2
      src/LibsslARC4Context.h
  83. 4 2
      src/LibsslARC4Decryptor.h
  84. 4 2
      src/LibsslARC4Encryptor.h
  85. 14 8
      src/LibsslDHKeyExchange.h
  86. 5 5
      src/Logger.h
  87. 17 12
      src/MSEHandshake.cc
  88. 8 3
      src/MessageDigestHelper.cc
  89. 14 14
      src/MetaFileUtil.cc
  90. 1 1
      src/MetalinkHelper.cc
  91. 1 1
      src/MetalinkPostDownloadHandler.cc
  92. 7 2
      src/MultiDiskAdaptor.cc
  93. 5 2
      src/NameMatchOptionHandler.h
  94. 3 2
      src/NameResolver.cc
  95. 7 3
      src/Netrc.cc
  96. 5 5
      src/NullLogger.h
  97. 21 18
      src/OptionHandlerImpl.h
  98. 1 1
      src/PStringSegment.cc
  99. 6 6
      src/ParameterizedStringParser.cc
  100. 4 5
      src/PeerAbstractCommand.cc

+ 11 - 0
ChangeLog

@@ -1,3 +1,14 @@
+2008-04-27  Tatsuhiro Tsujikawa  <tujikawa at rednoah dot com>
+
+	Rewritten Exception class. Throw exception object, not its pointer and
+	catch by reference, so that remove problematic delete operator for
+	catched exception.
+	* src/Exception.cc
+	* src/Exception.h
+	* test/ExceptionTest.cc
+	* src/*: All files throwing/catching exception.
+	* test/*: All files throwing/catching exception.
+
 2008-04-26  Tatsuhiro Tsujikawa  <tujikawa at rednoah dot com>
 
 	Now auto protocol detection is enabled without -Z option.

+ 12 - 15
src/AbstractCommand.cc

@@ -53,6 +53,7 @@
 #include "Socket.h"
 #include "message.h"
 #include "prefs.h"
+#include "StringFormat.h"
 
 namespace aria2 {
 
@@ -104,7 +105,7 @@ bool AbstractCommand::execute() {
     if(!peerStat.isNull()) {
       if(peerStat->getStatus() == PeerStat::REQUEST_IDLE) {
 	logger->info(MSG_ABORT_REQUESTED, cuid);
-	onAbort(0);
+	onAbort();
 	req->resetUrl();
 	tryReserved();
 	return true;
@@ -141,39 +142,35 @@ bool AbstractCommand::execute() {
       return executeInternal();
     } else {
       if(checkPoint.elapsed(timeout)) {
-	throw new DlRetryEx(EX_TIME_OUT);
+	throw DlRetryEx(EX_TIME_OUT);
       }
       e->commands.push_back(this);
       return false;
     }
-  } catch(DlAbortEx* err) {
+  } catch(DlAbortEx& err) {
     logger->error(MSG_DOWNLOAD_ABORTED, err, cuid, req->getUrl().c_str());
-    onAbort(err);
-    delete(err);
+    onAbort();
     req->resetUrl();
     tryReserved();
     return true;
-  } catch(DlRetryEx* err) {
+  } catch(DlRetryEx& err) {
     logger->info(MSG_RESTARTING_DOWNLOAD, err, cuid, req->getUrl().c_str());
     req->addTryCount();
     bool isAbort = e->option->getAsInt(PREF_MAX_TRIES) != 0 &&
       req->getTryCount() >= (unsigned int)e->option->getAsInt(PREF_MAX_TRIES);
     if(isAbort) {
-      onAbort(err);
+      onAbort();
     }
     if(isAbort) {
       logger->info(MSG_MAX_TRY, cuid, req->getTryCount());
       logger->error(MSG_DOWNLOAD_ABORTED, err, cuid, req->getUrl().c_str());
-      delete(err);
       tryReserved();
       return true;
     } else {
-      delete(err);
       return prepareForRetry(e->option->getAsInt(PREF_RETRY_WAIT));
     }
-  } catch(DownloadFailureException* err) {
+  } catch(DownloadFailureException& err) {
     logger->error(EX_EXCEPTION_CAUGHT, err);
-    delete(err);
     _requestGroup->setHaltRequested(true);
     return true;
   }
@@ -200,7 +197,7 @@ bool AbstractCommand::prepareForRetry(time_t wait) {
   return true;
 }
 
-void AbstractCommand::onAbort(Exception* ex) {
+void AbstractCommand::onAbort() {
   logger->debug(MSG_UNREGISTER_CUID, cuid);
   //_segmentMan->unregisterId(cuid);
   if(!_requestGroup->getPieceStorage().isNull()) {
@@ -278,9 +275,9 @@ bool AbstractCommand::resolveHostname(const std::string& hostname,
       return true;
       break;
     case NameResolver::STATUS_ERROR:
-      throw new DlAbortEx(MSG_NAME_RESOLUTION_FAILED, cuid,
-			  hostname.c_str(),
-			  resolver->getError().c_str());
+      throw DlAbortEx(StringFormat(MSG_NAME_RESOLUTION_FAILED, cuid,
+				   hostname.c_str(),
+				   resolver->getError().c_str()).str());
     default:
       return false;
     }

+ 1 - 1
src/AbstractCommand.h

@@ -62,7 +62,7 @@ protected:
 
   void tryReserved();
   virtual bool prepareForRetry(time_t wait);
-  virtual void onAbort(Exception* ex);
+  virtual void onAbort();
   virtual bool executeInternal() = 0;
 
   void setReadCheckSocket(const SharedHandle<SocketCore>& socket);

+ 12 - 8
src/AbstractDiskWriter.cc

@@ -40,6 +40,7 @@
 #include "Logger.h"
 #include "DlAbortEx.h"
 #include "a2io.h"
+#include "StringFormat.h"
 #include <cerrno>
 #include <cstring>
 #include <cassert>
@@ -79,11 +80,13 @@ void AbstractDiskWriter::openExistingFile(const std::string& filename,
   this->filename = filename;
   File f(filename);
   if(!f.isFile()) {
-    throw new DlAbortEx(EX_FILE_OPEN, filename.c_str(), MSG_FILE_NOT_FOUND);
+    throw DlAbortEx
+      (StringFormat(EX_FILE_OPEN, filename.c_str(), MSG_FILE_NOT_FOUND).str());
   }
 
   if((fd = open(filename.c_str(), O_RDWR|O_BINARY, OPEN_MODE)) < 0) {
-    throw new DlAbortEx(EX_FILE_OPEN, filename.c_str(), strerror(errno));
+    throw DlAbortEx
+      (StringFormat(EX_FILE_OPEN, filename.c_str(), strerror(errno)).str());
   }
 }
 
@@ -93,7 +96,7 @@ void AbstractDiskWriter::createFile(const std::string& filename, int addFlags)
   assert(filename.size());
   Util::mkdirs(File(filename).getDirname());
   if((fd = open(filename.c_str(), O_CREAT|O_RDWR|O_TRUNC|O_BINARY|addFlags, OPEN_MODE)) < 0) {
-    throw new DlAbortEx(EX_FILE_OPEN, filename.c_str(), strerror(errno));
+    throw DlAbortEx(StringFormat(EX_FILE_OPEN, filename.c_str(), strerror(errno)).str());
   }  
 }
 
@@ -121,7 +124,8 @@ ssize_t AbstractDiskWriter::readDataInternal(unsigned char* data, size_t len)
 void AbstractDiskWriter::seek(off_t offset)
 {
   if(offset != lseek(fd, offset, SEEK_SET)) {
-    throw new DlAbortEx(EX_FILE_SEEK, filename.c_str(), strerror(errno));
+    throw DlAbortEx
+      (StringFormat(EX_FILE_SEEK, filename.c_str(), strerror(errno)).str());
   }
 }
 
@@ -129,7 +133,7 @@ void AbstractDiskWriter::writeData(const unsigned char* data, size_t len, off_t
 {
   seek(offset);
   if(writeDataInternal(data, len) < 0) {
-    throw new DlAbortEx(EX_FILE_WRITE, filename.c_str(), strerror(errno));
+    throw DlAbortEx(StringFormat(EX_FILE_WRITE, filename.c_str(), strerror(errno)).str());
   }
 }
 
@@ -138,7 +142,7 @@ ssize_t AbstractDiskWriter::readData(unsigned char* data, size_t len, off_t offs
   ssize_t ret;
   seek(offset);
   if((ret = readDataInternal(data, len)) < 0) {
-    throw new DlAbortEx(EX_FILE_READ, filename.c_str(), strerror(errno));
+    throw DlAbortEx(StringFormat(EX_FILE_READ, filename.c_str(), strerror(errno)).str());
   }
   return ret;
 }
@@ -146,7 +150,7 @@ ssize_t AbstractDiskWriter::readData(unsigned char* data, size_t len, off_t offs
 void AbstractDiskWriter::truncate(uint64_t length)
 {
   if(fd == -1) {
-    throw new DlAbortEx("File not opened.");
+    throw DlAbortEx("File not opened.");
   }
   ftruncate(fd, length);
 }
@@ -155,7 +159,7 @@ void AbstractDiskWriter::truncate(uint64_t length)
 uint64_t AbstractDiskWriter::size() const
 {
   if(fd == -1) {
-    throw new DlAbortEx("File not opened.");
+    throw DlAbortEx("File not opened.");
   }
   struct stat fileStat;
   if(fstat(fd, &fileStat) < 0) {

+ 1 - 1
src/AbstractProxyResponseCommand.cc

@@ -66,7 +66,7 @@ bool AbstractProxyResponseCommand::executeInternal() {
     return false;
   }
   if(httpResponse->getResponseStatus() != "200") {
-    throw new DlRetryEx(EX_PROXY_CONNECTION_FAILED);
+    throw DlRetryEx(EX_PROXY_CONNECTION_FAILED);
   }
   e->commands.push_back(getNextCommand());
   return true;

+ 8 - 4
src/BtAllowedFastMessage.cc

@@ -38,16 +38,19 @@
 #include "DlAbortEx.h"
 #include "message.h"
 #include "Peer.h"
+#include "StringFormat.h"
 
 namespace aria2 {
 
 BtAllowedFastMessageHandle BtAllowedFastMessage::create(const unsigned char* data, size_t dataLength) {
   if(dataLength != 5) {
-    throw new DlAbortEx(EX_INVALID_PAYLOAD_SIZE, "allowed fast", dataLength, 5);
+    throw DlAbortEx
+      (StringFormat(EX_INVALID_PAYLOAD_SIZE, "allowed fast", dataLength, 5).str());
   }
   uint8_t id = PeerMessageUtil::getId(data);
   if(id != ID) {
-    throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "allowed fast", ID);
+    throw DlAbortEx
+      (StringFormat(EX_INVALID_BT_MESSAGE_ID, id, "allowed fast", ID).str());
   }
   BtAllowedFastMessageHandle message(new BtAllowedFastMessage());
   message->setIndex(PeerMessageUtil::getIntParam(data, 1));
@@ -56,8 +59,9 @@ BtAllowedFastMessageHandle BtAllowedFastMessage::create(const unsigned char* dat
 
 void BtAllowedFastMessage::doReceivedAction() {
   if(!peer->isFastExtensionEnabled()) {
-    throw new DlAbortEx("%s received while fast extension is disabled",
-			toString().c_str());
+    throw DlAbortEx
+      (StringFormat("%s received while fast extension is disabled",
+		    toString().c_str()).str());
   }
   peer->addPeerAllowedIndex(index);
 }

+ 5 - 2
src/BtBitfieldMessage.cc

@@ -38,6 +38,7 @@
 #include "DlAbortEx.h"
 #include "message.h"
 #include "Peer.h"
+#include "StringFormat.h"
 #include <cstring>
 
 namespace aria2 {
@@ -57,11 +58,13 @@ BtBitfieldMessageHandle
 BtBitfieldMessage::create(const unsigned char* data, size_t dataLength)
 {
   if(dataLength <= 1) {
-    throw new DlAbortEx(EX_INVALID_PAYLOAD_SIZE, "bitfield", dataLength, 1);
+    throw DlAbortEx
+      (StringFormat(EX_INVALID_PAYLOAD_SIZE, "bitfield", dataLength, 1).str());
   }
   uint8_t id = PeerMessageUtil::getId(data);
   if(id != ID) {
-    throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "bitfield", ID);
+    throw DlAbortEx
+      (StringFormat(EX_INVALID_BT_MESSAGE_ID, id, "bitfield", ID).str());
   }
   BtBitfieldMessageHandle message(new BtBitfieldMessage());
   message->setBitfield((unsigned char*)data+1, dataLength-1);

+ 5 - 2
src/BtCancelMessage.cc

@@ -38,16 +38,19 @@
 #include "DlAbortEx.h"
 #include "message.h"
 #include "BtMessageDispatcher.h"
+#include "StringFormat.h"
 
 namespace aria2 {
 
 BtCancelMessageHandle BtCancelMessage::create(const unsigned char* data, size_t dataLength) {
   if(dataLength != 13) {
-    throw new DlAbortEx(EX_INVALID_PAYLOAD_SIZE, "cancel", dataLength, 13);
+    throw DlAbortEx
+      (StringFormat(EX_INVALID_PAYLOAD_SIZE, "cancel", dataLength, 13).str());
   }
   uint8_t id = PeerMessageUtil::getId(data);
   if(id != ID) {
-    throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "cancel", ID);
+    throw DlAbortEx
+      (StringFormat(EX_INVALID_BT_MESSAGE_ID, id, "cancel", ID).str());
   }
   BtCancelMessageHandle message(new BtCancelMessage());
   message->setIndex(PeerMessageUtil::getIntParam(data, 1));

+ 5 - 2
src/BtChokeMessage.cc

@@ -39,16 +39,19 @@
 #include "Peer.h"
 #include "BtMessageDispatcher.h"
 #include "BtRequestFactory.h"
+#include "StringFormat.h"
 
 namespace aria2 {
 
 BtChokeMessageHandle BtChokeMessage::create(const unsigned char* data, size_t dataLength) {
   if(dataLength != 1) {
-    throw new DlAbortEx(EX_INVALID_PAYLOAD_SIZE, "choke", dataLength, 1);
+    throw DlAbortEx
+      (StringFormat(EX_INVALID_PAYLOAD_SIZE, "choke", dataLength, 1).str());
   }
   uint8_t id = PeerMessageUtil::getId(data);
   if(id != ID) {
-    throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "choke", ID);
+    throw DlAbortEx
+      (StringFormat(EX_INVALID_BT_MESSAGE_ID, id, "choke", ID).str());
   }
   BtChokeMessageHandle chokeMessage(new BtChokeMessage());
   return chokeMessage;

+ 1 - 2
src/BtDependency.cc

@@ -75,9 +75,8 @@ bool BtDependency::resolve()
 	btContext->setPeerIdPrefix(_option->get(PREF_PEER_ID_PREFIX));
       }
       btContext->setDir(_dependant->getDownloadContext()->getDir());
-    } catch(RecoverableException* e) {
+    } catch(RecoverableException& e) {
       _logger->error(EX_EXCEPTION_CAUGHT, e);
-      delete e;
       _logger->debug("BtDependency for GID#%d failed. Go without Bt.",
 		     _dependant->getGID());
       return true;

+ 5 - 2
src/BtExtendedMessage.cc

@@ -48,6 +48,7 @@
 #include "DlAbortEx.h"
 #include "message.h"
 #include "Util.h"
+#include "StringFormat.h"
 #include <cassert>
 #include <cstring>
 
@@ -100,11 +101,13 @@ BtExtendedMessage::create(const BtContextHandle& btContext,
 			  const unsigned char* data, size_t dataLength)
 {
   if(dataLength < 2) {
-    throw new DlAbortEx(MSG_TOO_SMALL_PAYLOAD_SIZE, "extended", dataLength);
+    throw DlAbortEx
+      (StringFormat(MSG_TOO_SMALL_PAYLOAD_SIZE, "extended", dataLength).str());
   }
   uint8_t id = PeerMessageUtil::getId(data);
   if(id != ID) {
-    throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "extended", ID);
+    throw DlAbortEx
+      (StringFormat(EX_INVALID_BT_MESSAGE_ID, id, "extended", ID).str());
   }
   ExtensionMessageFactoryHandle factory = EXTENSION_MESSAGE_FACTORY(btContext,
 								    peer);

+ 10 - 7
src/BtHandshakeMessageValidator.h

@@ -39,6 +39,7 @@
 #include "BtHandshakeMessage.h"
 #include "Util.h"
 #include "PeerMessageUtil.h"
+#include "StringFormat.h"
 #include <cstring>
 
 namespace aria2 {
@@ -58,17 +59,19 @@ public:
   virtual bool validate(Errors& error) {
     // TODO
     if(message->getPstrlen() != 19) {
-      throw new DlAbortEx("invalid handshake pstrlen=%u",
-			  message->getPstrlen());
+      throw DlAbortEx(StringFormat("invalid handshake pstrlen=%u",
+				   message->getPstrlen()).str());
     }
     if(memcmp(BtHandshakeMessage::BT_PSTR, message->getPstr(), 19) != 0) {
-      throw new DlAbortEx("invalid handshake pstr=%s",
-			  Util::urlencode(message->getPstr(), 19).c_str());
+      throw DlAbortEx
+	(StringFormat("invalid handshake pstr=%s",
+		      Util::urlencode(message->getPstr(), 19).c_str()).str());
     }
     if(memcmp(infoHash, message->getInfoHash(), 20) != 0) {
-      throw new DlAbortEx("invalid handshake info hash: expected:%s, actual:%s",
-			  Util::toHex(infoHash, 20).c_str(),
-			  Util::toHex(message->getInfoHash(), 20).c_str());
+      throw DlAbortEx
+	(StringFormat("invalid handshake info hash: expected:%s, actual:%s",
+		      Util::toHex(infoHash, 20).c_str(),
+		      Util::toHex(message->getInfoHash(), 20).c_str()).str());
     }
     return true;
   }

+ 8 - 4
src/BtHaveAllMessage.cc

@@ -37,16 +37,19 @@
 #include "PeerMessageUtil.h"
 #include "message.h"
 #include "Peer.h"
+#include "StringFormat.h"
 
 namespace aria2 {
 
 BtHaveAllMessageHandle BtHaveAllMessage::create(const unsigned char* data, size_t dataLength) {
   if(dataLength != 1) {
-    throw new DlAbortEx(EX_INVALID_PAYLOAD_SIZE, "have all", dataLength, 1);
+    throw DlAbortEx
+      (StringFormat(EX_INVALID_PAYLOAD_SIZE, "have all", dataLength, 1).str());
   }
   uint8_t id = PeerMessageUtil::getId(data);
   if(id != ID) {
-    throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "have all", ID);
+    throw DlAbortEx
+      (StringFormat(EX_INVALID_BT_MESSAGE_ID, id, "have all", ID).str());
   }
   BtHaveAllMessageHandle message(new BtHaveAllMessage());
   return message;
@@ -54,8 +57,9 @@ BtHaveAllMessageHandle BtHaveAllMessage::create(const unsigned char* data, size_
 
 void BtHaveAllMessage::doReceivedAction() {
   if(!peer->isFastExtensionEnabled()) {
-    throw new DlAbortEx("%s received while fast extension is disabled",
-			toString().c_str());
+    throw DlAbortEx
+      (StringFormat("%s received while fast extension is disabled",
+		    toString().c_str()).str());
   }
   peer->setAllBitfield();
 }

+ 5 - 2
src/BtHaveMessage.cc

@@ -38,16 +38,19 @@
 #include "DlAbortEx.h"
 #include "message.h"
 #include "Peer.h"
+#include "StringFormat.h"
 
 namespace aria2 {
 
 BtHaveMessageHandle BtHaveMessage::create(const unsigned char* data, size_t dataLength) {
   if(dataLength != 5) {
-    throw new DlAbortEx(EX_INVALID_PAYLOAD_SIZE, "have", dataLength, 5);
+    throw DlAbortEx
+      (StringFormat(EX_INVALID_PAYLOAD_SIZE, "have", dataLength, 5).str());
   }
   uint8_t id = PeerMessageUtil::getId(data);
   if(id != ID) {
-    throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "have", ID);
+    throw DlAbortEx
+      (StringFormat(EX_INVALID_BT_MESSAGE_ID, id, "have", ID).str());
   }
   BtHaveMessageHandle message(new BtHaveMessage());
   message->setIndex(PeerMessageUtil::getIntParam(data, 1));

+ 8 - 4
src/BtHaveNoneMessage.cc

@@ -37,16 +37,19 @@
 #include "PeerMessageUtil.h"
 #include "message.h"
 #include "Peer.h"
+#include "StringFormat.h"
 
 namespace aria2 {
 
 BtHaveNoneMessageHandle BtHaveNoneMessage::create(const unsigned char* data, size_t dataLength) {
   if(dataLength != 1) {
-    throw new DlAbortEx(EX_INVALID_PAYLOAD_SIZE, "have none", dataLength, 1);
+    throw DlAbortEx
+      (StringFormat(EX_INVALID_PAYLOAD_SIZE, "have none", dataLength, 1).str());
   }
   uint8_t id = PeerMessageUtil::getId(data);
   if(id != ID) {
-    throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "have none", ID);
+    throw DlAbortEx
+      (StringFormat(EX_INVALID_BT_MESSAGE_ID, id, "have none", ID).str());
   }
   BtHaveNoneMessageHandle message(new BtHaveNoneMessage());
   return message;
@@ -54,8 +57,9 @@ BtHaveNoneMessageHandle BtHaveNoneMessage::create(const unsigned char* data, siz
 
 void BtHaveNoneMessage::doReceivedAction() {
   if(!peer->isFastExtensionEnabled()) {
-    throw new DlAbortEx("%s received while fast extension is disabled",
-			toString().c_str());
+    throw DlAbortEx
+      (StringFormat("%s received while fast extension is disabled",
+		    toString().c_str()).str());
   }
 }
 

+ 5 - 2
src/BtInterestedMessage.cc

@@ -40,16 +40,19 @@
 #include "BtRegistry.h"
 #include "BtContext.h"
 #include "PeerStorage.h"
+#include "StringFormat.h"
 
 namespace aria2 {
 
 BtInterestedMessageHandle BtInterestedMessage::create(const unsigned char* data, size_t dataLength) {
   if(dataLength != 1) {
-    throw new DlAbortEx(EX_INVALID_PAYLOAD_SIZE, "interested", dataLength, 1);
+    throw DlAbortEx
+      (StringFormat(EX_INVALID_PAYLOAD_SIZE, "interested", dataLength, 1).str());
   }
   uint8_t id = PeerMessageUtil::getId(data);
   if(id != ID) {
-    throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "interested", ID);
+    throw DlAbortEx
+      (StringFormat(EX_INVALID_BT_MESSAGE_ID, id, "interested", ID).str());
   }
   BtInterestedMessageHandle message(new BtInterestedMessage());
   return message;

+ 5 - 2
src/BtNotInterestedMessage.cc

@@ -40,16 +40,19 @@
 #include "BtRegistry.h"
 #include "BtContext.h"
 #include "PeerStorage.h"
+#include "StringFormat.h"
 
 namespace aria2 {
 
 BtNotInterestedMessageHandle BtNotInterestedMessage::create(const unsigned char* data, size_t dataLength) {
   if(dataLength != 1) {
-    throw new DlAbortEx(EX_INVALID_PAYLOAD_SIZE, "not interested", dataLength, 1);
+    throw DlAbortEx
+      (StringFormat(EX_INVALID_PAYLOAD_SIZE, "not interested", dataLength, 1).str());
   }
   uint8_t id = PeerMessageUtil::getId(data);
   if(id != ID) {
-    throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "not interested", ID);
+    throw DlAbortEx
+      (StringFormat(EX_INVALID_BT_MESSAGE_ID, id, "not interested", ID).str());
   }
   BtNotInterestedMessageHandle message(new BtNotInterestedMessage());
   return message;

+ 7 - 4
src/BtPieceMessage.cc

@@ -50,6 +50,7 @@
 #include "BtMessageFactory.h"
 #include "BtRequestFactory.h"
 #include "PeerConnection.h"
+#include "StringFormat.h"
 #include <cstring>
 
 namespace aria2 {
@@ -63,11 +64,13 @@ void BtPieceMessage::setBlock(const unsigned char* block, size_t blockLength) {
 
 BtPieceMessageHandle BtPieceMessage::create(const unsigned char* data, size_t dataLength) {
   if(dataLength <= 9) {
-    throw new DlAbortEx(EX_INVALID_PAYLOAD_SIZE, "piece", dataLength, 9);
+    throw DlAbortEx
+      (StringFormat(EX_INVALID_PAYLOAD_SIZE, "piece", dataLength, 9).str());
   }
   uint8_t id = PeerMessageUtil::getId(data);
   if(id != ID) {
-    throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "piece", ID);
+    throw DlAbortEx
+      (StringFormat(EX_INVALID_BT_MESSAGE_ID, id, "piece", ID).str());
   }
   BtPieceMessageHandle message(new BtPieceMessage());
   message->setIndex(PeerMessageUtil::getIntParam(data, 1));
@@ -171,7 +174,7 @@ size_t BtPieceMessage::sendPieceData(off_t offset, size_t length) const {
   size_t writtenLength = 0;
   for(int i = 0; i < res.quot; i++) {
     if((size_t)pieceStorage->getDiskAdaptor()->readData(buf, BUF_SIZE, offset+i*BUF_SIZE) < BUF_SIZE) {
-      throw new DlAbortEx(EX_DATA_READ);
+      throw DlAbortEx(EX_DATA_READ);
     }
     size_t ws = peerConnection->sendMessage(buf, BUF_SIZE);
     writtenLength += ws;
@@ -181,7 +184,7 @@ size_t BtPieceMessage::sendPieceData(off_t offset, size_t length) const {
   }
   if(res.rem > 0) {
     if(pieceStorage->getDiskAdaptor()->readData(buf, res.rem, offset+res.quot*BUF_SIZE) < res.rem) {
-      throw new DlAbortEx(EX_DATA_READ);
+      throw DlAbortEx(EX_DATA_READ);
     }
     size_t ws = peerConnection->sendMessage(buf, res.rem);
     writtenLength += ws;

+ 5 - 2
src/BtPortMessage.cc

@@ -44,6 +44,7 @@
 #include "DHTTaskQueue.h"
 #include "DHTTaskFactory.h"
 #include "DHTTask.h"
+#include "StringFormat.h"
 
 namespace aria2 {
 
@@ -57,11 +58,13 @@ BtPortMessage::~BtPortMessage()
 SharedHandle<BtPortMessage> BtPortMessage::create(const unsigned char* data, size_t dataLength)
 {
   if(dataLength != 3) {
-    throw new DlAbortEx(EX_INVALID_PAYLOAD_SIZE, "port", dataLength, 3);
+    throw DlAbortEx
+      (StringFormat(EX_INVALID_PAYLOAD_SIZE, "port", dataLength, 3).str());
   }
   uint8_t id = PeerMessageUtil::getId(data);
   if(id != ID) {
-    throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "piece", ID);
+    throw DlAbortEx
+      (StringFormat(EX_INVALID_BT_MESSAGE_ID, id, "piece", ID).str());
   }
   uint16_t port = PeerMessageUtil::getShortIntParam(data, 1);
   SharedHandle<BtPortMessage> message(new BtPortMessage(port));

+ 1 - 1
src/BtPostDownloadHandler.cc

@@ -70,7 +70,7 @@ RequestGroups BtPostDownloadHandler::getNextRequestGroups(RequestGroup* requestG
     requestGroup->getPieceStorage()->getDiskAdaptor()->openExistingFile();
     content = Util::toString(requestGroup->getPieceStorage()->getDiskAdaptor());
     requestGroup->getPieceStorage()->getDiskAdaptor()->closeFile();    
-  } catch(Exception* e) {
+  } catch(Exception& e) {
     requestGroup->getPieceStorage()->getDiskAdaptor()->closeFile();
     throw;
   }

+ 9 - 5
src/BtRejectMessage.cc

@@ -40,16 +40,19 @@
 #include "Peer.h"
 #include "RequestSlot.h"
 #include "BtMessageDispatcher.h"
+#include "StringFormat.h"
 
 namespace aria2 {
 
 BtRejectMessageHandle BtRejectMessage::create(const unsigned char* data, size_t dataLength) {
   if(dataLength != 13) {
-    throw new DlAbortEx(EX_INVALID_PAYLOAD_SIZE, "reject", dataLength, 13);
+    throw DlAbortEx
+      (StringFormat(EX_INVALID_PAYLOAD_SIZE, "reject", dataLength, 13).str());
   }
   uint8_t id = PeerMessageUtil::getId(data);
   if(id != ID) {
-    throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "reject", ID);
+    throw DlAbortEx
+      (StringFormat(EX_INVALID_BT_MESSAGE_ID, id, "reject", ID).str());
   }
   BtRejectMessageHandle message(new BtRejectMessage());
   message->setIndex(PeerMessageUtil::getIntParam(data, 1));
@@ -60,14 +63,15 @@ BtRejectMessageHandle BtRejectMessage::create(const unsigned char* data, size_t
 
 void BtRejectMessage::doReceivedAction() {
   if(!peer->isFastExtensionEnabled()) {
-    throw new DlAbortEx("%s received while fast extension is disabled.",
-			toString().c_str());
+    throw DlAbortEx
+      (StringFormat("%s received while fast extension is disabled.",
+		    toString().c_str()).str());
   }
   // TODO Current implementation does not close a connection even if
   // a request for this reject message has never sent.
   RequestSlot slot = dispatcher->getOutstandingRequest(index, begin, length);
   if(RequestSlot::isNull(slot)) {
-    //throw new DlAbortEx("reject recieved, but it is not in the request slots.");
+    //throw DlAbortEx("reject recieved, but it is not in the request slots.");
   } else {
     dispatcher->removeOutstandingRequest(slot);
   }

+ 5 - 2
src/BtRequestMessage.cc

@@ -44,16 +44,19 @@
 #include "PieceStorage.h"
 #include "BtMessageDispatcher.h"
 #include "BtMessageFactory.h"
+#include "StringFormat.h"
 
 namespace aria2 {
 
 BtRequestMessageHandle BtRequestMessage::create(const unsigned char* data, size_t dataLength) {
   if(dataLength != 13) {
-    throw new DlAbortEx(EX_INVALID_PAYLOAD_SIZE, "request", dataLength, 13);
+    throw DlAbortEx
+      (StringFormat(EX_INVALID_PAYLOAD_SIZE, "request", dataLength, 13).str());
   }
   uint8_t id = PeerMessageUtil::getId(data);
   if(id != ID) {
-    throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "request", ID);
+    throw DlAbortEx
+      (StringFormat(EX_INVALID_BT_MESSAGE_ID, id, "request", ID).str());
   }
   BtRequestMessageHandle message(new BtRequestMessage());
   message->setIndex(PeerMessageUtil::getIntParam(data, 1));

+ 5 - 2
src/BtSuggestPieceMessage.cc

@@ -37,16 +37,19 @@
 #include "Util.h"
 #include "DlAbortEx.h"
 #include "message.h"
+#include "StringFormat.h"
 
 namespace aria2 {
 
 BtSuggestPieceMessageHandle BtSuggestPieceMessage::create(const unsigned char* data, size_t dataLength) {
   if(dataLength != 5) {
-    throw new DlAbortEx(EX_INVALID_PAYLOAD_SIZE, "suggest piece", dataLength, 5);
+    throw DlAbortEx
+      (StringFormat(EX_INVALID_PAYLOAD_SIZE, "suggest piece", dataLength, 5).str());
   }
   uint8_t id = PeerMessageUtil::getId(data);
   if(id != ID) {
-    throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "suggest piece", ID);
+    throw DlAbortEx
+      (StringFormat(EX_INVALID_BT_MESSAGE_ID, id, "suggest piece", ID).str());
   }
   BtSuggestPieceMessageHandle message(new BtSuggestPieceMessage());
   message->setIndex(PeerMessageUtil::getIntParam(data, 1));

+ 5 - 2
src/BtUnchokeMessage.cc

@@ -37,16 +37,19 @@
 #include "DlAbortEx.h"
 #include "message.h"
 #include "Peer.h"
+#include "StringFormat.h"
 
 namespace aria2 {
 
 BtUnchokeMessageHandle BtUnchokeMessage::create(const unsigned char* data, size_t dataLength) {
   if(dataLength != 1) {
-    throw new DlAbortEx(EX_INVALID_PAYLOAD_SIZE, "unchoke", dataLength, 1);
+    throw DlAbortEx
+      (StringFormat(EX_INVALID_PAYLOAD_SIZE, "unchoke", dataLength, 1).str());
   }
   uint8_t id = PeerMessageUtil::getId(data);
   if(id != ID) {
-    throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "unchoke", ID);
+    throw DlAbortEx
+      (StringFormat(EX_INVALID_BT_MESSAGE_ID, id, "unchoke", ID).str());
   }
   BtUnchokeMessageHandle message(new BtUnchokeMessage());
   return message;

+ 1 - 1
src/CheckIntegrityCommand.cc

@@ -79,7 +79,7 @@ bool CheckIntegrityCommand::executeInternal()
   }
 }
 
-bool CheckIntegrityCommand::handleException(Exception* e)
+bool CheckIntegrityCommand::handleException(Exception& e)
 {
   logger->error(MSG_FILE_VALIDATION_FAILURE, e, cuid);
   logger->error(MSG_DOWNLOAD_NOT_COMPLETE, cuid, _requestGroup->getFilePath().c_str());

+ 1 - 1
src/CheckIntegrityCommand.h

@@ -57,7 +57,7 @@ public:
 
   virtual bool executeInternal();
 
-  virtual bool handleException(Exception* e);
+  virtual bool handleException(Exception& e);
 };
 
 } // namespace aria2

+ 5 - 3
src/ChunkedEncoding.cc

@@ -36,6 +36,7 @@
 #include "DlAbortEx.h"
 #include "message.h"
 #include "Util.h"
+#include "StringFormat.h"
 #include <cstring>
 
 namespace aria2 {
@@ -144,7 +145,7 @@ int ChunkedEncoding::readDataEOL(unsigned char** pp) {
   } else if(strbufTail-*pp < 2) {
     return -1;
   } else {
-    throw new DlAbortEx(EX_INVALID_CHUNK_SIZE);
+    throw DlAbortEx(EX_INVALID_CHUNK_SIZE);
   }  
 }
 
@@ -166,7 +167,7 @@ int ChunkedEncoding::readChunkSize(unsigned char** pp) {
   std::string temp(*pp, exsp);
   chunkSize = Util::parseInt(temp, 16);
   if(chunkSize < 0) {
-    throw new DlAbortEx(EX_INVALID_CHUNK_SIZE);
+    throw DlAbortEx(EX_INVALID_CHUNK_SIZE);
   }
   *pp = p+2;
   return 0;
@@ -176,7 +177,8 @@ void ChunkedEncoding::addBuffer(const unsigned char* inbuf, size_t inlen) {
   size_t realbufSize = strbufTail-strbuf;
   if(realbufSize+inlen >= strbufSize) {
     if(realbufSize+inlen > MAX_BUFSIZE) {
-      throw new DlAbortEx(EX_TOO_LARGE_CHUNK, realbufSize+inlen);
+      throw DlAbortEx
+	(StringFormat(EX_TOO_LARGE_CHUNK, realbufSize+inlen).str());
     }
     strbufSize = realbufSize+inlen;
     unsigned char* temp = new unsigned char[strbufSize];

+ 1 - 2
src/CookieBoxFactory.cc

@@ -60,10 +60,9 @@ void CookieBoxFactory::loadDefaultCookie(std::istream& s)
       if(c.good()) {
 	defaultCookies.push_back(c);
       }
-    } catch(RecoverableException* e) {
+    } catch(RecoverableException& e) {
       // ignore malformed cookie entry
       // TODO better to log it
-      delete e;
     }
   }
 }

+ 6 - 4
src/DHTAnnouncePeerMessage.cc

@@ -45,6 +45,7 @@
 #include "DHTTokenTracker.h"
 #include "DlAbortEx.h"
 #include "BtConstants.h"
+#include "StringFormat.h"
 #include <cstring>
 
 namespace aria2 {
@@ -97,10 +98,11 @@ void DHTAnnouncePeerMessage::validate() const
   if(!_tokenTracker->validateToken(_token, _infoHash,
 				   _remoteNode->getIPAddress(),
 				   _remoteNode->getPort())) {
-    throw new DlAbortEx("Invalid token=%s from %s:%u",
-			Util::toHex(_token).c_str(),
-			_remoteNode->getIPAddress().c_str(),
-			_remoteNode->getPort());
+    throw DlAbortEx
+      (StringFormat("Invalid token=%s from %s:%u",
+		    Util::toHex(_token).c_str(),
+		    _remoteNode->getIPAddress().c_str(),
+		    _remoteNode->getPort()).str());
   }
 }
 

+ 1 - 2
src/DHTAutoSaveCommand.cc

@@ -117,10 +117,9 @@ void DHTAutoSaveCommand::save()
   } catch(std::ios::failure const& e) {
     logger->error("Failed to save DHT routing table to %s. cause:%s",
 		  tempFile.c_str(), strerror(errno));
-  } catch(RecoverableException* e) {
+  } catch(RecoverableException& e) {
     logger->error("Exception caught while saving DHT routing table to %s",
 		  e, tempFile.c_str());
-    delete e;
   }
 }
 

+ 1 - 2
src/DHTConnectionImpl.cc

@@ -71,9 +71,8 @@ bool DHTConnectionImpl::bind(uint16_t& port)
     port = svaddr.second;
     _logger->info("Bind socket for DHT. port=%u", port);
     return true;
-  } catch(RecoverableException* e) {
+  } catch(RecoverableException& e) {
     _logger->error("Failed to bind for DHT. port=%u", e, port);
-    delete e;
   }
   return false;
 }

+ 7 - 7
src/DHTEntryPointNameResolveCommand.cc

@@ -48,6 +48,7 @@
 #include "DHTTask.h"
 #include "RequestGroupMan.h"
 #include "Logger.h"
+#include "StringFormat.h"
 
 namespace aria2 {
 
@@ -95,9 +96,8 @@ bool DHTEntryPointNameResolveCommand::execute()
 	    return false;
 	  }
 	}
-      } catch(RecoverableException* e) {
+      } catch(RecoverableException& e) {
 	logger->error(EX_EXCEPTION_CAUGHT, e);
-	delete e;
 	_entryPoints.erase(_entryPoints.begin());
 	_resolver->reset();
       }
@@ -107,9 +107,8 @@ bool DHTEntryPointNameResolveCommand::execute()
       _taskQueue->addPeriodicTask1(_taskFactory->createNodeLookupTask(_localNode->getID()));
       _taskQueue->addPeriodicTask1(_taskFactory->createBucketRefreshTask());
     }
-  } catch(RecoverableException* e) {
+  } catch(RecoverableException& e) {
     logger->error(EX_EXCEPTION_CAUGHT, e);
-    delete e;
   }
   return true;
 }
@@ -142,9 +141,10 @@ bool DHTEntryPointNameResolveCommand::resolveHostname(const std::string& hostnam
       return true;
       break;
     case NameResolver::STATUS_ERROR:
-      throw new DlAbortEx(MSG_NAME_RESOLUTION_FAILED, cuid,
-			  hostname.c_str(),
-			  resolver->getError().c_str());
+      throw DlAbortEx
+	(StringFormat(MSG_NAME_RESOLUTION_FAILED, cuid,
+		      hostname.c_str(),
+		      resolver->getError().c_str()).str());
     default:
       return false;
     }

+ 1 - 2
src/DHTInteractionCommand.cc

@@ -84,9 +84,8 @@ bool DHTInteractionCommand::execute()
   _receiver->handleTimeout();
   try {
     _dispatcher->sendMessages();
-  } catch(RecoverableException* e) {
+  } catch(RecoverableException& e) {
     logger->error(EX_EXCEPTION_CAUGHT, e);
-    delete e;
   }
   _e->commands.push_back(this);
   return false;

+ 2 - 2
src/DHTMessageDispatcherImpl.cc

@@ -41,6 +41,7 @@
 #include "LogFactory.h"
 #include "Logger.h"
 #include "DHTConstants.h"
+#include "StringFormat.h"
 
 namespace aria2 {
 
@@ -75,9 +76,8 @@ DHTMessageDispatcherImpl::sendMessage(const SharedHandle<DHTMessageEntry>& entry
       _tracker->addMessage(entry->_message, entry->_timeout, entry->_callback);
     }
     _logger->info("Message sent: %s", entry->_message->toString().c_str());
-  } catch(RecoverableException* e) {
+  } catch(RecoverableException& e) {
     _logger->error("Failed to send message: %s", e, entry->_message->toString().c_str());
-    delete e;
   }
 }
 

+ 29 - 18
src/DHTMessageFactoryImpl.cc

@@ -59,6 +59,7 @@
 #include "Util.h"
 #include "Peer.h"
 #include "Logger.h"
+#include "StringFormat.h"
 #include <cstring>
 #include <utility>
 
@@ -87,7 +88,8 @@ static const Dictionary* getDictionary(const Dictionary* d, const std::string& k
   if(c) {
     return c;
   } else {
-    throw new DlAbortEx("Malformed DHT message. Missing %s", key.c_str());
+    throw DlAbortEx
+      (StringFormat("Malformed DHT message. Missing %s", key.c_str()).str());
   }
 }
 
@@ -97,7 +99,8 @@ static const Data* getData(const Dictionary* d, const std::string& key)
   if(c) {
     return c;
   } else {
-    throw new DlAbortEx("Malformed DHT message. Missing %s", key.c_str());
+    throw DlAbortEx
+      (StringFormat("Malformed DHT message. Missing %s", key.c_str()).str());
   }
 }
 
@@ -107,8 +110,9 @@ static const Data* getData(const List* l, size_t index)
   if(c) {
     return c;
   } else {
-    throw new DlAbortEx("Malformed DHT message. element[%u] is not Data.",
-			index);
+    throw DlAbortEx
+      (StringFormat("Malformed DHT message. element[%u] is not Data.",
+		    index).str());
   }
 }
 
@@ -118,33 +122,37 @@ static const List* getList(const Dictionary* d, const std::string& key)
   if(l) {
     return l;
   } else {
-    throw new DlAbortEx("Malformed DHT message. Missing %s", key.c_str());
+    throw DlAbortEx
+      (StringFormat("Malformed DHT message. Missing %s", key.c_str()).str());
   }
 }
 
 void DHTMessageFactoryImpl::validateID(const Data* id) const
 {
   if(id->getLen() != DHT_ID_LENGTH) {
-    throw new DlAbortEx("Malformed DHT message. Invalid ID length. Expected:%d, Actual:%d", DHT_ID_LENGTH, id->getLen());
+    throw DlAbortEx
+      (StringFormat("Malformed DHT message. Invalid ID length. Expected:%d, Actual:%d", DHT_ID_LENGTH, id->getLen()).str());
   }
 }
 
 void DHTMessageFactoryImpl::validateIDMatch(const unsigned char* expected, const unsigned char* actual) const
 {
   if(memcmp(expected, actual, DHT_ID_LENGTH) != 0) {
-    //throw new DlAbortEx("Different ID received.");
+    //throw DlAbortEx("Different ID received.");
   }
 }
 
 void DHTMessageFactoryImpl::validatePort(const Data* i) const
 {
   if(!i->isNumber()) {
-    throw new DlAbortEx("Malformed DHT message. Invalid port=%s",
-			Util::toHex(i->toString()).c_str());
+    throw DlAbortEx
+      (StringFormat("Malformed DHT message. Invalid port=%s",
+		    Util::toHex(i->toString()).c_str()).str());
   }
   uint32_t port = i->toInt();
   if(UINT16_MAX < port) {
-    throw new DlAbortEx("Malformed DHT message. Invalid port=%u", port);
+    throw DlAbortEx
+      (StringFormat("Malformed DHT message. Invalid port=%u", port).str());
   }
 }
 
@@ -157,7 +165,7 @@ SharedHandle<DHTMessage> DHTMessageFactoryImpl::createQueryMessage(const Diction
   const Data* y = getData(d, "y");
   const Dictionary* a = getDictionary(d, "a");
   if(y->toString() != "q") {
-    throw new DlAbortEx("Malformed DHT message. y != q");
+    throw DlAbortEx("Malformed DHT message. y != q");
   }
   const Data* id = getData(getDictionary(d, "a"), "id");
   validateID(id);
@@ -186,7 +194,8 @@ SharedHandle<DHTMessage> DHTMessageFactoryImpl::createQueryMessage(const Diction
 				     static_cast<uint16_t>(port->toInt()),
 				     token->toString(), transactionID);
   } else {
-    throw new DlAbortEx("Unsupported message type: %s", messageType.c_str());
+    throw DlAbortEx
+      (StringFormat("Unsupported message type: %s", messageType.c_str()).str());
   }
 }
 
@@ -207,10 +216,11 @@ DHTMessageFactoryImpl::createResponseMessage(const std::string& messageType,
     } else {
       _logger->debug("e doesn't have 2 elements.");
     }
-    throw new DlAbortEx("Received Error DHT message.");
+    throw DlAbortEx("Received Error DHT message.");
   } else if(y->toString() != "r") {
-    throw new DlAbortEx("Malformed DHT message. y != r: y=%s",
-			Util::urlencode(y->toString()).c_str());
+    throw DlAbortEx
+      (StringFormat("Malformed DHT message. y != r: y=%s",
+		    Util::urlencode(y->toString()).c_str()).str());
   }
   const Dictionary* r = getDictionary(d, "r");
   const Data* id = getData(r, "id");
@@ -231,13 +241,14 @@ DHTMessageFactoryImpl::createResponseMessage(const std::string& messageType,
       if(nodes) {
 	return createGetPeersReplyMessageWithNodes(remoteNode, d, transactionID);
       } else {
-	throw new DlAbortEx("Malformed DHT message: missing nodes/values");
+	throw DlAbortEx("Malformed DHT message: missing nodes/values");
       }
     }
   } else if(messageType == "announce_peer") {
     return createAnnouncePeerReplyMessage(remoteNode, transactionID);
   } else {
-    throw new DlAbortEx("Unsupported message type: %s", messageType.c_str());
+    throw DlAbortEx
+      (StringFormat("Unsupported message type: %s", messageType.c_str()).str());
   }
 }
 
@@ -292,7 +303,7 @@ std::deque<SharedHandle<DHTNode> >
 DHTMessageFactoryImpl::extractNodes(const unsigned char* src, size_t length)
 {
   if(length%26 != 0) {
-    throw new DlAbortEx("Nodes length is not multiple of 26");
+    throw DlAbortEx("Nodes length is not multiple of 26");
   }
   std::deque<SharedHandle<DHTNode> > nodes;
   for(size_t offset = 0; offset < length; offset += 26) {

+ 1 - 2
src/DHTMessageReceiver.cc

@@ -110,9 +110,8 @@ SharedHandle<DHTMessage> DHTMessageReceiver::receiveMessage()
       callback->onReceived(message);
     }
     return message;
-  } catch(RecoverableException* e) {
+  } catch(RecoverableException& e) {
     _logger->info("Exception thrown while receiving DHT message.", e);
-    delete e;
     return handleUnknownMessage(data, sizeof(data), remoteAddr, remotePort);
   }
 }

+ 4 - 3
src/DHTMessageTracker.cc

@@ -46,6 +46,7 @@
 #include "Data.h"
 #include "DlAbortEx.h"
 #include "DHTConstants.h"
+#include "StringFormat.h"
 #include <utility>
 
 namespace aria2 {
@@ -72,7 +73,8 @@ DHTMessageTracker::messageArrived(const Dictionary* d,
 {
   const Data* tid = dynamic_cast<const Data*>(d->get("t"));
   if(!tid) {
-    throw new DlAbortEx("Malformed DHT message. From:%s:%u", ipaddr.c_str(), port);
+    throw DlAbortEx(StringFormat("Malformed DHT message. From:%s:%u",
+				 ipaddr.c_str(), port).str());
   }
   _logger->debug("Searching tracker entry for TransactionID=%s, Remote=%s:%u",
 		 Util::toHex(tid->toString()).c_str(), ipaddr.c_str(), port);
@@ -119,9 +121,8 @@ void DHTMessageTracker::handleTimeout()
 	if(!callback.isNull()) {
 	  callback->onTimeout(node);
 	}
-      } catch(RecoverableException* e) {
+      } catch(RecoverableException& e) {
 	_logger->info("Exception thrown while handling timeouts.", e);
-	delete e;
       }
     } else {
       ++i;

+ 1 - 2
src/DHTPeerAnnounceCommand.cc

@@ -56,9 +56,8 @@ void DHTPeerAnnounceCommand::process()
 {
   try {
     _peerAnnounceStorage->handleTimeout();
-  } catch(RecoverableException* e) {
+  } catch(RecoverableException& e) {
     logger->error(EX_EXCEPTION_CAUGHT, e);
-    delete e;
   }
 }
 

+ 7 - 4
src/DHTRoutingTableDeserializer.cc

@@ -39,6 +39,7 @@
 #include "DlAbortEx.h"
 #include "Logger.h"
 #include "a2netcompat.h"
+#include "StringFormat.h"
 #include <cerrno>
 #include <cstring>
 #include <istream>
@@ -81,8 +82,9 @@ void DHTRoutingTableDeserializer::deserialize(std::istream& in)
     // header
     in.read(buf, 8);
     if(memcmp(header, buf, 8) != 0) {
-      throw new DlAbortEx("Failed to load DHT routing table. cause:%s",
-			  "bad header");
+      throw DlAbortEx
+	(StringFormat("Failed to load DHT routing table. cause:%s",
+		      "bad header").str());
     }
     // time
     in.read(buf, 4);
@@ -150,8 +152,9 @@ void DHTRoutingTableDeserializer::deserialize(std::istream& in)
     _localNode = localNode;
   } catch(std::ios::failure const& exception) {
     _nodes.clear();
-    throw new DlAbortEx("Failed to load DHT routing table. cause:%s",
-			strerror(errno));
+    throw DlAbortEx
+      (StringFormat("Failed to load DHT routing table. cause:%s",
+		    strerror(errno)).str());
   }
 }
 

+ 4 - 2
src/DHTRoutingTableSerializer.cc

@@ -39,6 +39,7 @@
 #include "PeerMessageUtil.h"
 #include "Logger.h"
 #include "a2netcompat.h"
+#include "StringFormat.h"
 #include <cerrno>
 #include <cstring>
 #include <ostream>
@@ -121,8 +122,9 @@ void DHTRoutingTableSerializer::serialize(std::ostream& o)
       o.write(zero, 4);
     }
   } catch(std::ios::failure const& exception) {
-    throw new DlAbortEx("Failed to save DHT routing table. cause:%s",
-			strerror(errno));
+    throw DlAbortEx
+      (StringFormat("Failed to save DHT routing table. cause:%s",
+		    strerror(errno)).str());
   }
 }
 

+ 3 - 5
src/DHTSetup.cc

@@ -93,10 +93,9 @@ Commands DHTSetup::setup(DownloadEngine* e, const Option* option)
 	in.exceptions(std::ios::failbit);
 	deserializer.deserialize(in);
 	localNode = deserializer.getLocalNode();
-      } catch(RecoverableException* e) {
+      } catch(RecoverableException& e) {
 	_logger->error("Exception caught while loading DHT routing table from %s",
 		       e, dhtFile.c_str());
-	delete e;
       }
     }
     if(localNode.isNull()) {
@@ -108,7 +107,7 @@ Commands DHTSetup::setup(DownloadEngine* e, const Option* option)
       IntSequence seq = Util::parseIntRange(option->get(PREF_DHT_LISTEN_PORT));
       uint16_t port;
       if(!connection->bind(port, seq)) {
-	throw new DlAbortEx("Error occurred while binding port for DHT");
+	throw DlAbortEx("Error occurred while binding port for DHT");
       }
       localNode->setPort(port);
     }
@@ -235,9 +234,8 @@ Commands DHTSetup::setup(DownloadEngine* e, const Option* option)
     _initialized = true;
 
     return commands;
-  } catch(RecoverableException* e) {
+  } catch(RecoverableException& e) {
     _logger->error("Exception caught while initializing DHT functionality. DHT is disabled.", e);
-    delete e;
     DHTRegistry::clear();
     return Commands();
   }

+ 4 - 2
src/DHTTokenTracker.cc

@@ -38,6 +38,7 @@
 #include "DlAbortEx.h"
 #include "DHTConstants.h"
 #include "MessageDigestHelper.h"
+#include "StringFormat.h"
 #include <cstring>
 
 namespace aria2 {
@@ -62,8 +63,9 @@ std::string DHTTokenTracker::generateToken(const unsigned char* infoHash,
 {
   unsigned char src[DHT_ID_LENGTH+6+SECRET_SIZE];
   if(!PeerMessageUtil::createcompact(src+DHT_ID_LENGTH, ipaddr, port)) {
-    throw new DlAbortEx("Token generation failed: ipaddr=%s, port=%u",
-			ipaddr.c_str(), port);
+    throw DlAbortEx
+      (StringFormat("Token generation failed: ipaddr=%s, port=%u",
+		    ipaddr.c_str(), port).str());
   }
   memcpy(src, infoHash, DHT_ID_LENGTH);
   memcpy(src+DHT_ID_LENGTH+6, secret, SECRET_SIZE);

+ 1 - 2
src/DHTTokenUpdateCommand.cc

@@ -58,9 +58,8 @@ void DHTTokenUpdateCommand::process()
 {
   try {
     _tokenTracker->updateTokenSecret();
-  } catch(RecoverableException* e) {
+  } catch(RecoverableException& e) {
     logger->error(EX_EXCEPTION_CAUGHT, e);
-    delete e;
   }
 }
 

+ 5 - 3
src/DefaultBtAnnounce.cc

@@ -52,6 +52,7 @@
 #include "PeerStorage.h"
 #include "Peer.h"
 #include "Option.h"
+#include "StringFormat.h"
 
 namespace aria2 {
 
@@ -198,12 +199,13 @@ DefaultBtAnnounce::processAnnounceResponse(const unsigned char* trackerResponse,
 							trackerResponseLength));
   const Dictionary* response = dynamic_cast<const Dictionary*>(entry.get());
   if(!response) {
-    throw new DlAbortEx(MSG_NULL_TRACKER_RESPONSE);
+    throw DlAbortEx(MSG_NULL_TRACKER_RESPONSE);
   }
   const Data* failureReasonData = dynamic_cast<const Data*>(response->get("failure reason"));
   if(failureReasonData) {
-    throw new DlAbortEx(EX_TRACKER_FAILURE,
-			failureReasonData->toString().c_str());
+    throw DlAbortEx
+      (StringFormat(EX_TRACKER_FAILURE,
+		    failureReasonData->toString().c_str()).str());
   }
   const Data* warningMessageData = dynamic_cast<const Data*>(response->get("warning message"));
   if(warningMessageData) {

+ 24 - 13
src/DefaultBtContext.cc

@@ -49,6 +49,7 @@
 #include "FileEntry.h"
 #include "message.h"
 #include "PeerMessageUtil.h"
+#include "StringFormat.h"
 #include <cstring>
 #include <ostream>
 #include <functional>
@@ -134,11 +135,13 @@ void DefaultBtContext::extractFileEntries(const Dictionary* infoDic,
       if(lengthData) {
 	length += lengthData->toLLInt();
       } else {
-	throw new DlAbortEx(MSG_SOMETHING_MISSING_IN_TORRENT, "file length");
+	throw DlAbortEx
+	  (StringFormat(MSG_SOMETHING_MISSING_IN_TORRENT, "file length").str());
       }
       const List* pathList = dynamic_cast<const List*>(fileDic->get("path"));
       if(!pathList) {
-	throw new DlAbortEx(MSG_SOMETHING_MISSING_IN_TORRENT, "file path list");
+	throw DlAbortEx
+	  (StringFormat(MSG_SOMETHING_MISSING_IN_TORRENT, "file path list").str());
       }
       const std::deque<MetaEntry*>& paths = pathList->getList();
       std::string path;
@@ -147,14 +150,16 @@ void DefaultBtContext::extractFileEntries(const Dictionary* infoDic,
 	if(subpath) {
 	  path += subpath->toString()+"/";
 	} else {
-	  throw new DlAbortEx(MSG_SOMETHING_MISSING_IN_TORRENT, "file path element");
+	  throw DlAbortEx
+	    (StringFormat(MSG_SOMETHING_MISSING_IN_TORRENT, "file path element").str());
 	}
       }
       const Data* lastPath = dynamic_cast<const Data*>(paths.back());
       if(lastPath) {
 	path += lastPath->toString();
       } else {
-	throw new DlAbortEx(MSG_SOMETHING_MISSING_IN_TORRENT, "file path element");
+	throw DlAbortEx
+	  (StringFormat(MSG_SOMETHING_MISSING_IN_TORRENT, "file path element").str());
       }
 
       std::deque<std::string> uris;
@@ -175,7 +180,8 @@ void DefaultBtContext::extractFileEntries(const Dictionary* infoDic,
     if(length) {
       totalLength = length->toLLInt();
     } else {
-      throw new DlAbortEx(MSG_SOMETHING_MISSING_IN_TORRENT, "file length");
+      throw DlAbortEx
+	(StringFormat(MSG_SOMETHING_MISSING_IN_TORRENT, "file length").str());
     }
     FileEntryHandle fileEntry(new FileEntry(name, totalLength, 0, urlList));
     fileEntries.push_back(fileEntry);
@@ -265,7 +271,8 @@ void DefaultBtContext::loadFromMemory(const unsigned char* content,
   SharedHandle<MetaEntry> rootEntry(MetaFileUtil::bdecoding(content, length));
   const Dictionary* rootDic = dynamic_cast<const Dictionary*>(rootEntry.get());
   if(!rootDic) {
-    throw new DlAbortEx("torrent file does not contain a root dictionary .");
+    throw DlAbortEx
+      (StringFormat("torrent file does not contain a root dictionary .").str());
   }
   processRootDictionary(rootDic, defaultName);
 }
@@ -274,7 +281,8 @@ void DefaultBtContext::load(const std::string& torrentFile) {
   SharedHandle<MetaEntry> rootEntry(MetaFileUtil::parseMetaFile(torrentFile));
   const Dictionary* rootDic = dynamic_cast<const Dictionary*>(rootEntry.get());
   if(!rootDic) {
-    throw new DlAbortEx("torrent file does not contain a root dictionary .");
+    throw DlAbortEx
+      (StringFormat("torrent file does not contain a root dictionary .").str());
   }
   processRootDictionary(rootDic, torrentFile);
 }
@@ -284,7 +292,8 @@ void DefaultBtContext::processRootDictionary(const Dictionary* rootDic, const st
   clear();
   const Dictionary* infoDic = dynamic_cast<const Dictionary*>(rootDic->get("info"));
   if(!infoDic) {
-    throw new DlAbortEx(MSG_SOMETHING_MISSING_IN_TORRENT, "info directory");
+    throw DlAbortEx
+      (StringFormat(MSG_SOMETHING_MISSING_IN_TORRENT, "info directory").str());
   }
   // retrieve infoHash
   BencodeVisitor v;
@@ -296,19 +305,21 @@ void DefaultBtContext::processRootDictionary(const Dictionary* rootDic, const st
   // calculate the number of pieces
   const Data* pieceHashData = dynamic_cast<const Data*>(infoDic->get("pieces"));
   if(!pieceHashData) {
-    throw new DlAbortEx(MSG_SOMETHING_MISSING_IN_TORRENT, "pieces");
+    throw DlAbortEx
+      (StringFormat(MSG_SOMETHING_MISSING_IN_TORRENT, "pieces").str());
   }
   if(pieceHashData->getLen() == 0) {
-    throw new DlAbortEx("The length of piece hash is 0.");
+    throw DlAbortEx("The length of piece hash is 0.");
   }
   numPieces = pieceHashData->getLen()/PIECE_HASH_LENGTH;
   if(numPieces == 0) {
-    throw new DlAbortEx("The number of pieces is 0.");
+    throw DlAbortEx("The number of pieces is 0.");
   }
   // retrieve piece length
   const Data* pieceLengthData = dynamic_cast<const Data*>(infoDic->get("piece length"));
   if(!pieceLengthData) {
-    throw new DlAbortEx(MSG_SOMETHING_MISSING_IN_TORRENT, "piece length");
+    throw DlAbortEx
+      (StringFormat(MSG_SOMETHING_MISSING_IN_TORRENT, "piece length").str());
   }
   pieceLength = pieceLengthData->toInt();
   // retrieve piece hashes
@@ -327,7 +338,7 @@ void DefaultBtContext::processRootDictionary(const Dictionary* rootDic, const st
   // retrieve file entries
   extractFileEntries(infoDic, defaultName, urlList);
   if((totalLength+pieceLength-1)/pieceLength != numPieces) {
-    throw new DlAbortEx("Too few/many piece hash.");
+    throw DlAbortEx("Too few/many piece hash.");
   }
   // retrieve announce
   const Data* announceData = dynamic_cast<const Data*>(rootDic->get("announce"));

+ 6 - 3
src/DefaultBtInteractive.cc

@@ -64,6 +64,7 @@
 #include "BtRegistry.h"
 #include "Logger.h"
 #include "LogFactory.h"
+#include "StringFormat.h"
 
 namespace aria2 {
 
@@ -351,7 +352,7 @@ void DefaultBtInteractive::detectMessageFlooding() {
   if(floodingCheckPoint.elapsed(FLOODING_CHECK_INTERVAL)) {
     if(floodingStat.getChokeUnchokeCount() >= 2 ||
        floodingStat.getKeepAliveCount() >= 2) {
-      throw new DlAbortEx(EX_FLOODING_DETECTED);
+      throw DlAbortEx(EX_FLOODING_DETECTED);
     } else {
       floodingStat.reset();
     }
@@ -368,7 +369,8 @@ void DefaultBtInteractive::checkActiveInteraction()
     if(!peer->amInterested() && !peer->peerInterested() &&
        inactiveCheckPoint.elapsed(interval)) {
       // TODO change the message
-      throw new DlAbortEx("Disconnect peer because we are not interested each other after %u second(s).", interval);
+      throw DlAbortEx
+	(StringFormat("Disconnect peer because we are not interested each other after %u second(s).", interval).str());
     }
   }
   // Since the peers which are *just* connected and do nothing to improve
@@ -377,7 +379,8 @@ void DefaultBtInteractive::checkActiveInteraction()
   {
     time_t interval = 2*60;
     if(inactiveCheckPoint.elapsed(interval)) {
-      throw new DlAbortEx(EX_DROP_INACTIVE_CONNECTION, interval);
+      throw DlAbortEx
+	(StringFormat(EX_DROP_INACTIVE_CONNECTION, interval).str());
     }
   }
 }

+ 3 - 2
src/DefaultBtMessageFactory.cc

@@ -68,6 +68,7 @@
 #include "BtRegistry.h"
 #include "BtContext.h"
 #include "PieceStorage.h"
+#include "StringFormat.h"
 
 namespace aria2 {
 
@@ -194,12 +195,12 @@ DefaultBtMessageFactory::createBtMessage(const unsigned char* data, size_t dataL
       if(peer->isExtendedMessagingEnabled()) {
 	msg = BtExtendedMessage::create(btContext, peer, data, dataLength);
       } else {
-	throw new DlAbortEx("Received extended message from peer during a session with extended messaging disabled.");
+	throw DlAbortEx("Received extended message from peer during a session with extended messaging disabled.");
       }
       break;
     }
     default:
-      throw new DlAbortEx("Invalid message ID. id=%u", id);
+      throw DlAbortEx(StringFormat("Invalid message ID. id=%u", id).str());
     }
   }
   setCommonProperty(msg);

+ 33 - 23
src/DefaultBtProgressInfoFile.cc

@@ -51,6 +51,7 @@
 #include "Util.h"
 #include "a2io.h"
 #include "DownloadFailureException.h"
+#include "StringFormat.h"
 #include <fstream>
 #include <cerrno>
 #include <cstring>
@@ -149,12 +150,12 @@ void DefaultBtProgressInfoFile::save() {
     _logger->info(MSG_SAVED_SEGMENT_FILE);
   } catch(std::ios::failure const& exception) {
     // TODO std::ios::failure doesn't give us the reasons of failure...
-    throw new DlAbortEx(EX_SEGMENT_FILE_WRITE,
-			_filename.c_str(), strerror(errno));
+    throw DlAbortEx(StringFormat(EX_SEGMENT_FILE_WRITE,
+				 _filename.c_str(), strerror(errno)).str());
   }
   if(!File(filenameTemp).renameTo(_filename)) {
-    throw new DlAbortEx(EX_SEGMENT_FILE_WRITE,
-			_filename.c_str(), strerror(errno));
+    throw DlAbortEx(StringFormat(EX_SEGMENT_FILE_WRITE,
+				 _filename.c_str(), strerror(errno)).str());
   }
 }
 
@@ -169,8 +170,9 @@ void DefaultBtProgressInfoFile::load()
     unsigned char version[2];
     in.read((char*)version, sizeof(version));
     if(std::string("0000") != Util::toHex(version, sizeof(version))) {
-      throw new DlAbortEx("Unsupported ctrl file version: %s",
-			  Util::toHex(version, sizeof(version)).c_str());
+      throw DlAbortEx
+	(StringFormat("Unsupported ctrl file version: %s",
+		      Util::toHex(version, sizeof(version)).c_str()).str());
     }
     unsigned char extension[4];
     in.read((char*)extension, sizeof(extension));
@@ -184,7 +186,8 @@ void DefaultBtProgressInfoFile::load()
     uint32_t infoHashLength;
     in.read(reinterpret_cast<char*>(&infoHashLength), sizeof(infoHashLength));
     if((infoHashLength < 0) || ((infoHashLength == 0) && infoHashCheckEnabled)) {
-      throw new DlAbortEx("Invalid info hash length: %d", infoHashLength);
+      throw DlAbortEx
+	(StringFormat("Invalid info hash length: %d", infoHashLength).str());
     }
     if(infoHashLength > 0) {
       savedInfoHash = new unsigned char[infoHashLength];
@@ -192,9 +195,10 @@ void DefaultBtProgressInfoFile::load()
       BtContextHandle btContext(dynamic_pointer_cast<BtContext>(_dctx));
       if(infoHashCheckEnabled &&
 	 Util::toHex(savedInfoHash, infoHashLength) != btContext->getInfoHashAsString()) {
-	throw new DlAbortEx("info hash mismatch. expected: %s, actual: %s",
-			    btContext->getInfoHashAsString().c_str(),
-			    Util::toHex(savedInfoHash, infoHashLength).c_str());
+	throw DlAbortEx
+	  (StringFormat("info hash mismatch. expected: %s, actual: %s",
+			btContext->getInfoHashAsString().c_str(),
+			Util::toHex(savedInfoHash, infoHashLength).c_str()).str());
       }
       delete [] savedInfoHash;
       savedInfoHash = 0;
@@ -206,9 +210,10 @@ void DefaultBtProgressInfoFile::load()
     uint64_t totalLength;
     in.read(reinterpret_cast<char*>(&totalLength), sizeof(totalLength));
     if(totalLength != _dctx->getTotalLength()) {
-      throw new DlAbortEx("total length mismatch. expected: %s, actual: %s",
-			  Util::itos(_dctx->getTotalLength()).c_str(),
-			  Util::itos(totalLength).c_str());
+      throw DlAbortEx
+	(StringFormat("total length mismatch. expected: %s, actual: %s",
+		      Util::itos(_dctx->getTotalLength()).c_str(),
+		      Util::itos(totalLength).c_str()).str());
     }
     uint64_t uploadLength;
     in.read(reinterpret_cast<char*>(&uploadLength), sizeof(uploadLength));
@@ -221,9 +226,10 @@ void DefaultBtProgressInfoFile::load()
     in.read(reinterpret_cast<char*>(&bitfieldLength), sizeof(bitfieldLength));
     uint32_t expectedBitfieldLength = ((totalLength+pieceLength-1)/pieceLength+7)/8;
     if(expectedBitfieldLength != bitfieldLength) {
-      throw new DlAbortEx("bitfield length mismatch. expected: %d, actual: %d",
-			  expectedBitfieldLength,
-			  bitfieldLength);
+      throw DlAbortEx
+	(StringFormat("bitfield length mismatch. expected: %d, actual: %d",
+		      expectedBitfieldLength,
+		      bitfieldLength).str());
     }
 
     savedBitfield = new unsigned char[bitfieldLength];
@@ -242,19 +248,22 @@ void DefaultBtProgressInfoFile::load()
 	uint32_t index;
 	in.read(reinterpret_cast<char*>(&index), sizeof(index));
 	if(!(index < _dctx->getNumPieces())) {
-	  throw new DlAbortEx("piece index out of range: %u", index);
+	  throw DlAbortEx
+	    (StringFormat("piece index out of range: %u", index).str());
 	}
 	uint32_t length;
 	in.read(reinterpret_cast<char*>(&length), sizeof(length));
 	if(!(length <=_dctx->getPieceLength())) {
-	  throw new DlAbortEx("piece length out of range: %u", length);
+	  throw DlAbortEx
+	    (StringFormat("piece length out of range: %u", length).str());
 	}
 	PieceHandle piece(new Piece(index, length));
 	uint32_t bitfieldLength;
 	in.read(reinterpret_cast<char*>(&bitfieldLength), sizeof(bitfieldLength));
 	if(piece->getBitfieldLength() != bitfieldLength) {
-	  throw new DlAbortEx("piece bitfield length mismatch. expected: %u actual: %u",
-			      piece->getBitfieldLength(), bitfieldLength);
+	  throw DlAbortEx
+	    (StringFormat("piece bitfield length mismatch. expected: %u actual: %u",
+			  piece->getBitfieldLength(), bitfieldLength).str());
 	}
 	savedBitfield = new unsigned char[bitfieldLength];
 	in.read(reinterpret_cast<char*>(savedBitfield), bitfieldLength);
@@ -272,7 +281,8 @@ void DefaultBtProgressInfoFile::load()
       src.setBitfield(savedBitfield, bitfieldLength);
       if((src.getCompletedLength() || numInFlightPiece) &&
 	 !_option->getAsBool(PREF_ALLOW_PIECE_LENGTH_CHANGE)) {
-	throw new DownloadFailureException("WARNING: Detected a change in piece length. You can proceed with --allow-piece-length-change=true, but you may lose some download progress.");
+	throw DownloadFailureException
+	  ("WARNING: Detected a change in piece length. You can proceed with --allow-piece-length-change=true, but you may lose some download progress.");
       }
       BitfieldMan dest(_dctx->getPieceLength(), totalLength);
       Util::convertBitfield(&dest, &src);
@@ -285,8 +295,8 @@ void DefaultBtProgressInfoFile::load()
     delete [] savedBitfield;
     delete [] savedInfoHash;
     // TODO std::ios::failure doesn't give us the reasons of failure...
-    throw new DlAbortEx(EX_SEGMENT_FILE_READ,
-			_filename.c_str(), strerror(errno));
+    throw DlAbortEx(StringFormat(EX_SEGMENT_FILE_READ,
+				 _filename.c_str(), strerror(errno)).str());
   } 
 }
 

+ 7 - 3
src/DefaultExtensionMessageFactory.cc

@@ -41,6 +41,7 @@
 #include "LogFactory.h"
 #include "Logger.h"
 #include "BtRegistry.h"
+#include "StringFormat.h"
 
 namespace aria2 {
 
@@ -68,8 +69,9 @@ DefaultExtensionMessageFactory::createMessage(const unsigned char* data, size_t
   } else {
     std::string extensionName = getExtensionName(extensionMessageID);
     if(extensionName.empty()) {
-      throw new DlAbortEx("No extension registered for extended message ID %u",
-			  extensionMessageID);
+      throw DlAbortEx
+	(StringFormat("No extension registered for extended message ID %u",
+		      extensionMessageID).str());
     }
     if(extensionName == "ut_pex") {
       // uTorrent compatible Peer-Exchange
@@ -78,7 +80,9 @@ DefaultExtensionMessageFactory::createMessage(const unsigned char* data, size_t
       m->setBtContext(_btContext);
       return m;
     } else {
-      throw new DlAbortEx("Unsupported extension message received. extensionMessageID=%u, extensionName=%s", extensionMessageID, extensionName.c_str());
+      throw DlAbortEx
+	(StringFormat("Unsupported extension message received. extensionMessageID=%u, extensionName=%s",
+		      extensionMessageID, extensionName.c_str()).str());
     }
   }
 }

+ 2 - 1
src/DefaultPieceStorage.cc

@@ -52,6 +52,7 @@
 #include "Util.h"
 #include "a2functional.h"
 #include "Option.h"
+#include "StringFormat.h"
 #include <numeric>
 #include <algorithm>
 
@@ -367,7 +368,7 @@ void DefaultPieceStorage::setFileFilter(const std::deque<std::string>& filePaths
   for(std::deque<std::string>::const_iterator pitr = filePaths.begin();
       pitr != filePaths.end(); pitr++) {
     if(!diskAdaptor->addDownloadEntry(*pitr)) {
-      throw new DlAbortEx(EX_NO_SUCH_FILE_ENTRY, (*pitr).c_str());
+      throw DlAbortEx(StringFormat(EX_NO_SUCH_FILE_ENTRY, (*pitr).c_str()).str());
     }
     FileEntryHandle fileEntry = diskAdaptor->getFileEntryFromPath(*pitr);
     bitfieldMan->addFilter(fileEntry->getOffset(), fileEntry->getLength());

+ 2 - 1
src/DiskAdaptor.cc

@@ -38,6 +38,7 @@
 #include "Logger.h"
 #include "message.h"
 #include "DlAbortEx.h"
+#include "StringFormat.h"
 
 namespace aria2 {
 
@@ -53,7 +54,7 @@ FileEntryHandle DiskAdaptor::getFileEntryFromPath(const std::string& fileEntryPa
       return *itr;
     }
   }
-  throw new DlAbortEx(EX_NO_SUCH_FILE_ENTRY, fileEntryPath.c_str());
+  throw DlAbortEx(StringFormat(EX_NO_SUCH_FILE_ENTRY, fileEntryPath.c_str()).str());
 }
 
 bool DiskAdaptor::addDownloadEntry(const std::string& fileEntryPath)

+ 11 - 16
src/DlAbortEx.h

@@ -38,23 +38,18 @@
 
 namespace aria2 {
 
-class DlAbortEx : public RecoverableException {
-public:
-  DlAbortEx(Exception* cause = 0):RecoverableException(cause) {}
-
-  DlAbortEx(const char* msg, ...) {
-    va_list ap;
-    va_start(ap, msg);
-    setMsg(msg, ap);
-    va_end(ap);
-  }
-
-  DlAbortEx(Exception* cause, const char* msg, ...):RecoverableException(cause) {
-    va_list ap;
-    va_start(ap, msg);
-    setMsg(msg, ap);
-    va_end(ap);
+class DlAbortEx:public RecoverableException {
+protected:
+  virtual SharedHandle<Exception> copy() const
+  {
+    SharedHandle<Exception> e(new DlAbortEx(*this));
+    return e;
   }
+public:
+  DlAbortEx(const std::string& msg):RecoverableException(msg) {}
+  DlAbortEx(const std::string& msg,
+	    const Exception& cause):RecoverableException(msg, cause) {}
+  DlAbortEx(const RecoverableException& e):RecoverableException(e) {}
 };
 
 } // namespace aria2

+ 11 - 16
src/DlRetryEx.h

@@ -38,23 +38,18 @@
 
 namespace aria2 {
 
-class DlRetryEx : public RecoverableException {
-public:
-  DlRetryEx(Exception* cause = 0):RecoverableException(cause) {}
-
-  DlRetryEx(const char* msg, ...) {
-    va_list ap;
-    va_start(ap, msg);
-    setMsg(msg, ap);
-    va_end(ap);
-  }
-
-  DlRetryEx(Exception* cause, const char* msg, ...):RecoverableException(cause) {
-    va_list ap;
-    va_start(ap, msg);
-    setMsg(msg, ap);
-    va_end(ap);
+class DlRetryEx:public RecoverableException {
+protected:
+  virtual SharedHandle<Exception> copy() const
+  {
+    SharedHandle<Exception> e(new DlRetryEx(*this));
+    return e;
   }
+public:
+  DlRetryEx(const std::string& msg):RecoverableException(msg) {}
+  DlRetryEx(const std::string& msg,
+	    const Exception& cause):RecoverableException(msg, cause) {}
+  DlRetryEx(const DlRetryEx& e):RecoverableException(e) {}
 };
 
 } // namespace aria2

+ 8 - 6
src/DownloadCommand.cc

@@ -54,6 +54,7 @@
 #include "Socket.h"
 #include "message.h"
 #include "prefs.h"
+#include "StringFormat.h"
 #ifdef ENABLE_MESSAGE_DIGEST
 # include "MessageDigestHelper.h"
 #endif // ENABLE_MESSAGE_DIGEST
@@ -138,7 +139,7 @@ bool DownloadCommand::executeInternal() {
     peerStat->updateDownloadLength(infbufSize);
   }
   if(_requestGroup->getTotalLength() != 0 && bufSize == 0) {
-    throw new DlRetryEx(EX_GOT_EOF);
+    throw DlRetryEx(EX_GOT_EOF);
   }
   if((!transferDecoder.isNull() && transferDecoder->finished())
      || (transferDecoder.isNull() && segment->complete())
@@ -162,10 +163,10 @@ void DownloadCommand::checkLowestDownloadSpeed() const
   if(peerStat->getDownloadStartTime().elapsed(startupIdleTime)) {
     unsigned int nowSpeed = peerStat->calculateDownloadSpeed();
     if(lowestDownloadSpeedLimit > 0 &&  nowSpeed <= lowestDownloadSpeedLimit) {
-      throw new DlAbortEx(EX_TOO_SLOW_DOWNLOAD_SPEED,
-			  nowSpeed,
-			  lowestDownloadSpeedLimit,
-			  req->getHost().c_str());
+      throw DlAbortEx(StringFormat(EX_TOO_SLOW_DOWNLOAD_SPEED,
+				   nowSpeed,
+				   lowestDownloadSpeedLimit,
+				   req->getHost().c_str()).str());
     }
   }
 }
@@ -221,7 +222,8 @@ void DownloadCommand::validatePieceHash(const SegmentHandle& segment)
 		   actualPieceHash.c_str());
       segment->clear();
       _requestGroup->getSegmentMan()->cancelSegment(cuid);
-      throw new DlRetryEx("Invalid checksum index=%d", segment->getIndex());
+      throw DlRetryEx
+	(StringFormat("Invalid checksum index=%d", segment->getIndex()).str());
     }
   } else
 #endif // ENABLE_MESSAGE_DIGEST

+ 11 - 16
src/DownloadFailureException.h

@@ -42,23 +42,18 @@ namespace aria2 {
  * Throw this exception when a RequestGroup should aborted.
  * FYI, DlAbortEx is the exception to abort 1 Request.
  */
-class DownloadFailureException : public RecoverableException {
-public:
-  DownloadFailureException(Exception* cause = 0):RecoverableException(cause) {}
-
-  DownloadFailureException(const char* msg, ...) {
-    va_list ap;
-    va_start(ap, msg);
-    setMsg(msg, ap);
-    va_end(ap);
-  }
-
-  DownloadFailureException(Exception* cause, const char* msg, ...):RecoverableException(cause) {
-    va_list ap;
-    va_start(ap, msg);
-    setMsg(msg, ap);
-    va_end(ap);
+class DownloadFailureException:public RecoverableException {
+protected:
+  virtual SharedHandle<Exception> copy() const
+  {
+    SharedHandle<Exception> e(new DownloadFailureException(*this));
+    return e;
   }
+public:
+  DownloadFailureException(const std::string& msg):RecoverableException(msg) {}
+  DownloadFailureException(const std::string& msg,
+			   const Exception& cause):RecoverableException(msg, cause) {}
+  DownloadFailureException(const DownloadFailureException& e):RecoverableException(e) {}
 };
 
 } // namespace aria2

+ 27 - 6
src/Exception.cc

@@ -33,17 +33,38 @@
  */
 /* copyright --> */
 #include "Exception.h"
-#include <ostream>
 
 namespace aria2 {
 
-std::ostream& operator<<(std::ostream& o, const Exception& e)
+Exception::Exception(const std::string& msg):exception(), _msg(msg) {}
+
+Exception::Exception(const std::string& msg,
+		     const Exception& cause):
+  exception(), _msg(msg), _cause(cause.copy()) {}
+
+Exception::Exception(const Exception& e):_msg(e._msg), _cause(e._cause)
+{}
+
+Exception::~Exception() throw() {}
+
+const char* Exception::what() const throw()
+{
+  return _msg.c_str();
+}
+
+std::string Exception::stackTrace() const throw()
 {
-  o << e.getMsg() << "\n";
-  for(Exception* cause = e.getCause(); cause; cause = cause->getCause()) {
-    o << "Cause: " << cause->getMsg() << "\n";
+  std::string stackTrace = "Exception: ";
+  stackTrace += what();
+  stackTrace += "\n";
+  SharedHandle<Exception> e = _cause;
+  while(!e.isNull()) {
+    stackTrace += "  -> ";
+    stackTrace += e->what();
+    stackTrace += "\n";
+    e = e->_cause;
   }
-  return o;
+  return stackTrace;
 }
 
 } // namespace aria2

+ 14 - 18
src/Exception.h

@@ -36,36 +36,32 @@
 #define _D_EXCEPTION_H_
 
 #include "common.h"
+#include "SharedHandle.h"
 #include <string>
-#include <cstdio>
-#include <cstdarg>
-#include <iosfwd>
 
 namespace aria2 {
 
-class Exception {
+class Exception:public std::exception {
 private:
-  std::string msg;
+  std::string _msg;
+
+  SharedHandle<Exception> _cause;
+
 protected:
-  Exception* cause;
+  virtual SharedHandle<Exception> copy() const = 0;
 
-  void setMsg(const std::string& msgsrc, va_list ap) {
-    char buf[1024];
-    vsnprintf(buf, sizeof(buf), msgsrc.c_str(), ap);
-    msg = buf;
-  }
 public:
-  Exception(Exception* cause = 0):cause(cause) {}
+  Exception(const std::string& msg);
+
+  Exception(const std::string& msg, const Exception& cause);
 
-  virtual ~Exception() {
-    delete cause;
-  }
+  Exception(const Exception& e);
 
-  const std::string& getMsg() const { return msg; }
+  virtual ~Exception() throw();
 
-  Exception* getCause() const { return cause; }
+  virtual const char* what() const throw();
 
-  friend std::ostream& operator<<(std::ostream& o, const Exception& e);
+  std::string stackTrace() const throw();
 };
 
 } // namespace aria2

+ 4 - 4
src/ExpatMetalinkProcessor.cc

@@ -125,20 +125,20 @@ ExpatMetalinkProcessor::parseFromBinaryStream(const SharedHandle<BinaryStream>&
 	break;
       }
       if(XML_Parse(parser, (const char*)buf, res, 0) == XML_STATUS_ERROR) {
-	throw new DlAbortEx(MSG_CANNOT_PARSE_METALINK);
+	throw DlAbortEx(MSG_CANNOT_PARSE_METALINK);
       }
       readOffset += res;
     }
     if(XML_Parse(parser, 0, 0, 1) == XML_STATUS_ERROR) {
-      throw new DlAbortEx(MSG_CANNOT_PARSE_METALINK);
+      throw DlAbortEx(MSG_CANNOT_PARSE_METALINK);
     }
-  } catch(Exception* e) {
+  } catch(Exception& e) {
     XML_ParserFree(parser);
     throw;
   }
   XML_ParserFree(parser);
   if(!_stm->finished()) {
-    throw new DlAbortEx(MSG_CANNOT_PARSE_METALINK);
+    throw DlAbortEx(MSG_CANNOT_PARSE_METALINK);
   }
   return _stm->getResult();
 }

+ 11 - 16
src/FatalException.h

@@ -38,23 +38,18 @@
 
 namespace aria2 {
 
-class FatalException : public Exception {
-public:
-  FatalException(Exception* cause = 0):Exception(cause) {}
-
-  FatalException(const char* msg, ...):Exception() {
-    va_list ap;
-    va_start(ap, msg);
-    setMsg(msg, ap);
-    va_end(ap);
-  }
-
-  FatalException(Exception* cause, const char* msg, ...):Exception(cause) {
-    va_list ap;
-    va_start(ap, msg);
-    setMsg(msg, ap);
-    va_end(ap);
+class FatalException:public Exception {
+protected:
+  virtual SharedHandle<Exception> copy() const
+  {
+    SharedHandle<Exception> e(new FatalException(*this));
+    return e;
   }
+public:
+  FatalException(const std::string& msg):Exception(msg) {}
+  FatalException(const std::string& msg,
+		 const Exception& cause):Exception(msg, cause) {}
+  FatalException(const FatalException& e):Exception(e) {}
 };
 
 } // namespace aria2

+ 1 - 1
src/FileAllocationCommand.cc

@@ -71,7 +71,7 @@ bool FileAllocationCommand::executeInternal()
   }
 }
 
-bool FileAllocationCommand::handleException(Exception* e)
+bool FileAllocationCommand::handleException(Exception& e)
 {
   _e->_fileAllocationMan->markCurrentFileAllocationEntryDone();
   logger->error(MSG_FILE_ALLOCATION_FAILURE, e, cuid);

+ 1 - 1
src/FileAllocationCommand.h

@@ -56,7 +56,7 @@ public:
 
   virtual bool executeInternal();
 
-  virtual bool handleException(Exception* e);
+  virtual bool handleException(Exception& e);
 };
 
 } // namespace aria2

+ 1 - 2
src/FileMetalinkParserState.cc

@@ -65,8 +65,7 @@ void FileMetalinkParserState::beginElement(MetalinkParserStateMachine* stm,
       } else {
 	try {
 	  maxConnections = Util::parseInt((*itr).second);
-	} catch(RecoverableException* e) {
-	  delete e;
+	} catch(RecoverableException& e) {
 	  maxConnections = -1;
 	}
       }

+ 1 - 2
src/FillRequestGroupCommand.cc

@@ -61,9 +61,8 @@ bool FillRequestGroupCommand::execute()
   }
   try {
     _e->_requestGroupMan->fillRequestGroupFromReserver(_e);
-  } catch(RecoverableException* ex) {
+  } catch(RecoverableException& ex) {
     logger->error(EX_EXCEPTION_CAUGHT, ex);
-    delete ex;
   }
   if(_e->_requestGroupMan->downloadFinished()) {
     return true;

+ 3 - 3
src/FtpConnection.cc

@@ -184,7 +184,7 @@ bool FtpConnection::bulkReceiveResponse(std::pair<unsigned int, std::string>& re
     size_t size = sizeof(buf)-1;
     socket->readData(buf, size);
     if(size == 0) {
-      throw new DlRetryEx(EX_GOT_EOF);
+      throw DlRetryEx(EX_GOT_EOF);
     }
     buf[size] = '\0';
     strbuf += buf;
@@ -193,7 +193,7 @@ bool FtpConnection::bulkReceiveResponse(std::pair<unsigned int, std::string>& re
   if(strbuf.size() >= 4) {
     status = getStatus(strbuf);
     if(status == 0) {
-      throw new DlAbortEx(EX_INVALID_RESPONSE);
+      throw DlAbortEx(EX_INVALID_RESPONSE);
     }
   } else {
     return false;
@@ -262,7 +262,7 @@ unsigned int FtpConnection::receivePasvResponse(std::pair<std::string, uint16_t>
 	// port number
 	dest.second = 256*p1+p2;
       } else {
-	throw new DlRetryEx(EX_INVALID_RESPONSE);
+	throw DlRetryEx(EX_INVALID_RESPONSE);
       }
     }
     return response.first;

+ 1 - 1
src/FtpInitiateConnectionCommand.cc

@@ -102,7 +102,7 @@ bool FtpInitiateConnectionCommand::executeInternal() {
       command = new FtpTunnelRequestCommand(cuid, req, _requestGroup, e, socket);
     } else {
       // TODO
-      throw new DlAbortEx("ERROR");
+      throw DlAbortEx("ERROR");
     }
   } else {
     logger->info(MSG_CONNECTING_TO_SERVER, cuid, req->getHost().c_str(),

+ 16 - 13
src/FtpNegotiationCommand.cc

@@ -53,6 +53,7 @@
 #include "DownloadFailureException.h"
 #include "ServerHost.h"
 #include "Socket.h"
+#include "StringFormat.h"
 #include <stdint.h>
 #include <cassert>
 #include <utility>
@@ -115,7 +116,7 @@ bool FtpNegotiationCommand::recvGreeting() {
     return false;
   }
   if(status != 220) {
-    throw new DlAbortEx(EX_CONNECTION_FAILED);
+    throw DlAbortEx(EX_CONNECTION_FAILED);
   }
   sequence = SEQ_SEND_USER;
 
@@ -140,7 +141,7 @@ bool FtpNegotiationCommand::recvUser() {
     sequence = SEQ_SEND_PASS;
     break;
   default:
-    throw new DlAbortEx(EX_BAD_STATUS, status);
+    throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str());
   }
   return true;
 }
@@ -157,7 +158,7 @@ bool FtpNegotiationCommand::recvPass() {
     return false;
   }
   if(status != 230) {
-    throw new DlAbortEx(EX_BAD_STATUS, status);
+    throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str());
   }
   sequence = SEQ_SEND_TYPE;
   return true;
@@ -175,7 +176,7 @@ bool FtpNegotiationCommand::recvType() {
     return false;
   }
   if(status != 200) {
-    throw new DlAbortEx(EX_BAD_STATUS, status);
+    throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str());
   }
   sequence = SEQ_SEND_CWD;
   return true;
@@ -193,7 +194,7 @@ bool FtpNegotiationCommand::recvCwd() {
     return false;
   }
   if(status != 250) {
-    throw new DlAbortEx(EX_BAD_STATUS, status);
+    throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str());
   }
   sequence = SEQ_SEND_SIZE;
   return true;
@@ -212,10 +213,11 @@ bool FtpNegotiationCommand::recvSize() {
     return false;
   }
   if(status != 213) {
-    throw new DlAbortEx(EX_BAD_STATUS, status);
+    throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str());
   }
   if(size > INT64_MAX) {
-    throw new DlAbortEx(EX_TOO_LARGE_FILE, Util::uitos(size, true).c_str());
+    throw DlAbortEx
+      (StringFormat(EX_TOO_LARGE_FILE, Util::uitos(size, true).c_str()).str());
   }
   if(_requestGroup->getPieceStorage().isNull()) {
     SingleFileDownloadContextHandle dctx =
@@ -224,8 +226,9 @@ bool FtpNegotiationCommand::recvSize() {
     dctx->setFilename(Util::urldecode(req->getFile()));
     _requestGroup->preDownloadProcessing();
     if(e->_requestGroupMan->isSameFileBeingDownloaded(_requestGroup)) {
-      throw new DownloadFailureException(EX_DUPLICATE_FILE_DOWNLOAD,
-					 _requestGroup->getFilePath().c_str());
+      throw DownloadFailureException
+	(StringFormat(EX_DUPLICATE_FILE_DOWNLOAD,
+		      _requestGroup->getFilePath().c_str()).str());
     }
 
     _requestGroup->initPieceStorage();
@@ -280,7 +283,7 @@ bool FtpNegotiationCommand::recvPort() {
     return false;
   }
   if(status != 200) {
-    throw new DlAbortEx(EX_BAD_STATUS, status);
+    throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str());
   }
   sequence = SEQ_SEND_REST;
   return true;
@@ -300,7 +303,7 @@ bool FtpNegotiationCommand::recvPasv() {
     return false;
   }
   if(status != 227) {
-    throw new DlAbortEx(EX_BAD_STATUS, status);
+    throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str());
   }
   // make a data connection to the server.
   logger->info(MSG_CONNECTING_TO_SERVER, cuid,
@@ -336,7 +339,7 @@ bool FtpNegotiationCommand::recvRest() {
   }
   // TODO if we recieve negative response, then we set _requestGroup->getSegmentMan()->splittable = false, and continue.
   if(status != 350) {
-    throw new DlAbortEx(EX_BAD_STATUS, status);
+    throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str());
   }
   sequence = SEQ_SEND_RETR;
   return true;
@@ -354,7 +357,7 @@ bool FtpNegotiationCommand::recvRetr() {
     return false;
   }
   if(status != 150 && status != 125) {
-    throw new DlAbortEx(EX_BAD_STATUS, status);
+    throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str());
   }
   if(e->option->getAsBool(PREF_FTP_PASV)) {
     sequence = SEQ_NEGOTIATION_COMPLETED;

+ 5 - 3
src/HandshakeExtensionMessage.cc

@@ -44,6 +44,7 @@
 #include "LogFactory.h"
 #include "Logger.h"
 #include "message.h"
+#include "StringFormat.h"
 
 namespace aria2 {
 
@@ -133,8 +134,9 @@ HandshakeExtensionMessageHandle
 HandshakeExtensionMessage::create(const unsigned char* data, size_t length)
 {
   if(length < 1) {
-    throw new DlAbortEx(MSG_TOO_SMALL_PAYLOAD_SIZE,
-			EXTENSION_NAME.c_str(), length);
+    throw DlAbortEx
+      (StringFormat(MSG_TOO_SMALL_PAYLOAD_SIZE,
+		    EXTENSION_NAME.c_str(), length).str());
   }
   HandshakeExtensionMessageHandle msg(new HandshakeExtensionMessage());
   msg->_logger->debug("Creating HandshakeExtensionMessage from %s",
@@ -142,7 +144,7 @@ HandshakeExtensionMessage::create(const unsigned char* data, size_t length)
   SharedHandle<MetaEntry> root(MetaFileUtil::bdecoding(data+1, length-1));
   Dictionary* d = dynamic_cast<Dictionary*>(root.get());
   if(d == 0) {
-    throw new DlAbortEx("Unexpected payload format for extended message handshake");
+    throw DlAbortEx("Unexpected payload format for extended message handshake");
   }
   const Data* p = dynamic_cast<const Data*>(d->get("p"));
   if(p) {

+ 1 - 1
src/HelpItemFactory.cc

@@ -461,7 +461,7 @@ TagContainerHandle HelpItemFactory::createHelpItems(const Option* op)
   {
     HelpItemHandle item(new HelpItem("help", TEXT_HELP, TAG_BASIC));
     item->setAvailableValues
-      (StringFormat("%s,%s,%s,%s,%s,%s,all", TAG_BASIC, TAG_ADVANCED, TAG_HTTP, TAG_FTP, TAG_METALINK, TAG_BITTORRENT).toString());
+      (StringFormat("%s,%s,%s,%s,%s,%s,all", TAG_BASIC, TAG_ADVANCED, TAG_HTTP, TAG_FTP, TAG_METALINK, TAG_BITTORRENT).str());
     item->addTag(TAG_BASIC);
     tc->addItem(item);
   }

+ 2 - 2
src/HttpConnection.cc

@@ -112,7 +112,7 @@ void HttpConnection::sendProxyRequest(const HttpRequestHandle& httpRequest)
 HttpResponseHandle HttpConnection::receiveResponse()
 {
   if(outstandingHttpRequests.size() == 0) {
-    throw new DlAbortEx(EX_NO_HTTP_REQUEST_ENTRY_FOUND);
+    throw DlAbortEx(EX_NO_HTTP_REQUEST_ENTRY_FOUND);
   }
   HttpRequestEntryHandle entry = outstandingHttpRequests.front();
   HttpHeaderProcessorHandle proc = entry->getHttpHeaderProcessor();
@@ -121,7 +121,7 @@ HttpResponseHandle HttpConnection::receiveResponse()
   size_t size = sizeof(buf);
   socket->peekData(buf, size);
   if(size == 0) {
-    throw new DlRetryEx(EX_INVALID_RESPONSE);
+    throw DlRetryEx(EX_INVALID_RESPONSE);
   }
   proc->update(buf, size);
   if(!proc->eoh()) {

+ 2 - 2
src/HttpHeaderProcessor.cc

@@ -61,7 +61,7 @@ void HttpHeaderProcessor::checkHeaderLimit(size_t incomingLength)
 {
   strm.seekg(0, std::ios::end);
   if((size_t)strm.tellg()+incomingLength > _limit) {
-    throw new DlAbortEx("Too large http header");
+    throw DlAbortEx("Too large http header");
   }
 }
 
@@ -100,7 +100,7 @@ SharedHandle<HttpHeader> HttpHeaderProcessor::getHttpResponseHeader()
   getline(strm, line);  
   // check HTTP status value
   if(line.size() <= 12) {
-    throw new DlRetryEx(EX_NO_STATUS_HEADER);
+    throw DlRetryEx(EX_NO_STATUS_HEADER);
   }
   HttpHeaderHandle httpHeader(new HttpHeader());
   httpHeader->setResponseStatus(line.substr(9, 3));

+ 1 - 1
src/HttpInitiateConnectionCommand.cc

@@ -100,7 +100,7 @@ bool HttpInitiateConnectionCommand::executeInternal() {
 				       httpConnection, e, socket);
     } else {
       // TODO
-      throw new DlAbortEx("ERROR");
+      throw DlAbortEx("ERROR");
     }
   } else {
     SharedHandle<SocketCore> pooledSocket =

+ 17 - 11
src/HttpResponse.cc

@@ -45,6 +45,7 @@
 #include "Util.h"
 #include "message.h"
 #include "DlAbortEx.h"
+#include "StringFormat.h"
 #include <deque>
 
 namespace aria2 {
@@ -59,30 +60,35 @@ void HttpResponse::validateResponse() const
 {
   const std::string& status = getResponseStatus();
   if(status == "401") {
-    throw new DlAbortEx(EX_AUTH_FAILED);
+    throw DlAbortEx(EX_AUTH_FAILED);
   }
   if(status == "404") {
-    throw new DlAbortEx(MSG_RESOURCE_NOT_FOUND);
+    throw DlAbortEx(MSG_RESOURCE_NOT_FOUND);
   }
   if(status >= "400") {
-    throw new DlAbortEx(EX_BAD_STATUS, Util::parseUInt(status));
+    throw DlAbortEx
+      (StringFormat(EX_BAD_STATUS, Util::parseUInt(status)).str());
   }
   if(status >= "300") {
     if(!httpHeader->defined("Location")) {
-      throw new DlAbortEx(EX_LOCATION_HEADER_REQUIRED, Util::parseUInt(status));
+      throw DlAbortEx
+	(StringFormat(EX_LOCATION_HEADER_REQUIRED,
+		      Util::parseUInt(status)).str());
     }
   } else {
     if(!httpHeader->defined("Transfer-Encoding")) {
       // compare the received range against the requested range
       RangeHandle responseRange = httpHeader->getRange();
       if(!httpRequest->isRangeSatisfied(responseRange)) {
-	throw new DlAbortEx(EX_INVALID_RANGE_HEADER,
-			    Util::itos(httpRequest->getStartByte(), true).c_str(),
-			    Util::itos(httpRequest->getEndByte(), true).c_str(),
-			    Util::uitos(httpRequest->getEntityLength(), true).c_str(),
-			    Util::itos(responseRange->getStartByte(), true).c_str(),
-			    Util::itos(responseRange->getEndByte(), true).c_str(),
-			    Util::uitos(responseRange->getEntityLength(), true).c_str());
+	throw DlAbortEx
+	  (StringFormat(EX_INVALID_RANGE_HEADER,
+			Util::itos(httpRequest->getStartByte(), true).c_str(),
+			Util::itos(httpRequest->getEndByte(), true).c_str(),
+			Util::uitos(httpRequest->getEntityLength(), true).c_str(),
+			Util::itos(responseRange->getStartByte(), true).c_str(),
+			Util::itos(responseRange->getEndByte(), true).c_str(),
+			Util::uitos(responseRange->getEntityLength(), true).c_str()
+			).str());
       }
     }
   }

+ 8 - 5
src/HttpResponseCommand.cc

@@ -59,6 +59,7 @@
 #include "Socket.h"
 #include "message.h"
 #include "prefs.h"
+#include "StringFormat.h"
 
 namespace aria2 {
 
@@ -105,8 +106,9 @@ bool HttpResponseCommand::executeInternal()
     dctx->setContentType(httpResponse->getContentType());
     _requestGroup->preDownloadProcessing();
     if(e->_requestGroupMan->isSameFileBeingDownloaded(_requestGroup)) {
-      throw new DownloadFailureException(EX_DUPLICATE_FILE_DOWNLOAD,
-					 _requestGroup->getFilePath().c_str());
+      throw DownloadFailureException
+	(StringFormat(EX_DUPLICATE_FILE_DOWNLOAD,
+		      _requestGroup->getFilePath().c_str()).str());
     }
     if(totalLength == 0 || httpResponse->isTransferEncodingSpecified()) {
       // we ignore content-length when transfer-encoding is set
@@ -157,7 +159,7 @@ bool HttpResponseCommand::handleDefaultEncoding(const HttpResponseHandle& httpRe
       _requestGroup->getSegmentMan()->cancelSegment(cuid);
     }
     prepareForNextAction(command);
-  } catch(Exception* e) {
+  } catch(Exception& e) {
     delete command;
     throw;
   }
@@ -183,8 +185,9 @@ HttpDownloadCommand* HttpResponseCommand::createHttpDownloadCommand(const HttpRe
   if(httpResponse->isTransferEncodingSpecified()) {
     enc = httpResponse->getTransferDecoder();
     if(enc.isNull()) {
-      throw new DlAbortEx(EX_TRANSFER_ENCODING_NOT_SUPPORTED,
-			  httpResponse->getTransferEncoding().c_str());
+      throw DlAbortEx
+	(StringFormat(EX_TRANSFER_ENCODING_NOT_SUPPORTED,
+		      httpResponse->getTransferEncoding().c_str()).str());
     }
     enc->init();
   }

+ 4 - 1
src/InitiateConnectionCommandFactory.cc

@@ -39,6 +39,7 @@
 #include "RequestGroup.h"
 #include "DownloadEngine.h"
 #include "DlAbortEx.h"
+#include "StringFormat.h"
 
 namespace aria2 {
 
@@ -55,7 +56,9 @@ InitiateConnectionCommandFactory::createInitiateConnectionCommand(int32_t cuid,
     return new FtpInitiateConnectionCommand(cuid, req, requestGroup, e);
   } else {
     // these protocols are not supported yet
-    throw new DlAbortEx("%s is not supported yet.", req->getProtocol().c_str());
+    throw DlAbortEx
+      (StringFormat("%s is not supported yet.",
+		    req->getProtocol().c_str()).str());
   }
 }
 

+ 1 - 1
src/InitiatorMSEHandshakeCommand.cc

@@ -167,7 +167,7 @@ bool InitiatorMSEHandshakeCommand::prepareForNextPeer(time_t wait)
   }
 }
 
-void InitiatorMSEHandshakeCommand::onAbort(Exception* ex)
+void InitiatorMSEHandshakeCommand::onAbort()
 {
   if(e->option->getAsBool(PREF_BT_REQUIRE_CRYPTO)) {
     peerStorage->returnPeer(peer);

+ 1 - 1
src/InitiatorMSEHandshakeCommand.h

@@ -61,7 +61,7 @@ private:
 protected:
   virtual bool executeInternal();
   virtual bool prepareForNextPeer(time_t wait);
-  virtual void onAbort(Exception* ex);
+  virtual void onAbort();
   virtual bool exitBeforeExecute();
 public:
   InitiatorMSEHandshakeCommand(int32_t cuid,

+ 5 - 4
src/IteratableChunkChecksumValidator.cc

@@ -45,6 +45,7 @@
 #include "LogFactory.h"
 #include "Logger.h"
 #include "messageDigest.h"
+#include "StringFormat.h"
 #include <cerrno>
 
 namespace aria2 {
@@ -74,9 +75,8 @@ void IteratableChunkChecksumValidator::validateChunk()
     std::string actualChecksum;
     try {
       actualChecksum = calculateActualChecksum();
-    } catch(RecoverableException* ex) {
+    } catch(RecoverableException& ex) {
       _logger->debug("Caught exception while validating piece index=%d. Some part of file may be missing. Continue operation.", ex, _currentIndex);
-      delete ex;
       _bitfield->unsetBit(_currentIndex);
       _currentIndex++;
       return;
@@ -143,8 +143,9 @@ std::string IteratableChunkChecksumValidator::digest(off_t offset, size_t length
     size_t r = _pieceStorage->getDiskAdaptor()->readData(_buffer, BUFSIZE,
 							 curoffset);
     if(r == 0) {
-      throw new DlAbortEx(EX_FILE_READ, _dctx->getActualBasePath().c_str(),
-			  strerror(errno));
+      throw DlAbortEx
+	(StringFormat(EX_FILE_READ, _dctx->getActualBasePath().c_str(),
+		      strerror(errno)).str());
     }
     size_t wlength;
     if(max < curoffset+r) {

+ 4 - 2
src/LibgcryptARC4Context.h

@@ -37,6 +37,7 @@
 
 #include "common.h"
 #include "DlAbortEx.h"
+#include "StringFormat.h"
 #include <gcrypt.h>
 
 namespace aria2 {
@@ -47,8 +48,9 @@ private:
 
   void handleError(gcry_error_t err) const
   {
-    throw new DlAbortEx("Exception in libgcrypt routine(ARC4Context class): %s",
-			gcry_strerror(err));
+    throw DlAbortEx
+      (StringFormat("Exception in libgcrypt routine(ARC4Context class): %s",
+		    gcry_strerror(err)).str());
   }
 public:
   LibgcryptARC4Context():_cipherCtx(0) {}

+ 4 - 2
src/LibgcryptARC4Decryptor.h

@@ -38,6 +38,7 @@
 #include "common.h"
 #include "DlAbortEx.h"
 #include "LibgcryptARC4Context.h"
+#include "StringFormat.h"
 #include <gcrypt.h>
 
 namespace aria2 {
@@ -48,8 +49,9 @@ private:
 
   void handleError(gcry_error_t err) const
   {
-    throw new DlAbortEx("Exception in libgcrypt routine(ARC4Decryptor class): %s",
-			gcry_strerror(err));
+    throw DlAbortEx
+      (StringFormat("Exception in libgcrypt routine(ARC4Decryptor class): %s",
+		    gcry_strerror(err)).str());
   }
 public:
   ARC4Decryptor() {}

+ 4 - 2
src/LibgcryptARC4Encryptor.h

@@ -38,6 +38,7 @@
 #include "common.h"
 #include "DlAbortEx.h"
 #include "LibgcryptARC4Context.h"
+#include "StringFormat.h"
 #include <gcrypt.h>
 
 namespace aria2 {
@@ -48,8 +49,9 @@ private:
 
   void handleError(gcry_error_t err) const
   {
-    throw new DlAbortEx("Exception in libgcrypt routine(ARC4Encryptor class): %s",
-			gcry_strerror(err));
+    throw DlAbortEx
+      (StringFormat("Exception in libgcrypt routine(ARC4Encryptor class): %s",
+		    gcry_strerror(err)).str());
   }
 public:
   ARC4Encryptor() {}

+ 10 - 6
src/LibgcryptDHKeyExchange.h

@@ -37,6 +37,7 @@
 
 #include "common.h"
 #include "DlAbortEx.h"
+#include "StringFormat.h"
 #include <gcrypt.h>
 
 namespace aria2 {
@@ -55,8 +56,9 @@ private:
 
   void handleError(gcry_error_t err) const
   {
-    throw new DlAbortEx("Exception in libgcrypt routine(DHKeyExchange class): %s",
-			gcry_strerror(err));
+    throw DlAbortEx
+      (StringFormat("Exception in libgcrypt routine(DHKeyExchange class): %s",
+		    gcry_strerror(err)).str());
   }
 public:
   DHKeyExchange():
@@ -110,8 +112,9 @@ public:
   size_t getPublicKey(unsigned char* out, size_t outLength) const
   {
     if(outLength < _keyLength) {
-      throw new DlAbortEx("Insufficient buffer for public key. expect:%u, actual:%u",
-			  _keyLength, outLength);
+      throw DlAbortEx
+	(StringFormat("Insufficient buffer for public key. expect:%u, actual:%u",
+		      _keyLength, outLength).str());
     }
     memset(out, 0, outLength);
     size_t publicKeyBytes = (gcry_mpi_get_nbits(_publicKey)+7)/8;
@@ -135,8 +138,9 @@ public:
 		       size_t peerPublicKeyLength) const
   {
     if(outLength < _keyLength) {
-      throw new DlAbortEx("Insufficient buffer for secret. expect:%u, actual:%u",
-			  _keyLength, outLength);
+      throw DlAbortEx
+	(StringFormat("Insufficient buffer for secret. expect:%u, actual:%u",
+		      _keyLength, outLength).str());
     }
     gcry_mpi_t peerPublicKey;
     {

+ 4 - 2
src/LibsslARC4Context.h

@@ -37,6 +37,7 @@
 
 #include "common.h"
 #include "DlAbortEx.h"
+#include "StringFormat.h"
 #include <openssl/evp.h>
 #include <openssl/err.h>
 
@@ -48,8 +49,9 @@ private:
 
   void handleError() const
   {
-    throw new DlAbortEx("Exception in libssl routine(ARC4Context class): %s",
-			ERR_error_string(ERR_get_error(), 0));
+    throw DlAbortEx
+      (StringFormat("Exception in libssl routine(ARC4Context class): %s",
+		    ERR_error_string(ERR_get_error(), 0)).str());
   }
 public:
   LibsslARC4Context():_cipherCtx(0) {}

+ 4 - 2
src/LibsslARC4Decryptor.h

@@ -38,6 +38,7 @@
 #include "common.h"
 #include "DlAbortEx.h"
 #include "LibsslARC4Context.h"
+#include "StringFormat.h"
 #include <openssl/evp.h>
 #include <openssl/err.h>
 
@@ -49,8 +50,9 @@ private:
 
   void handleError() const
   {
-    throw new DlAbortEx("Exception in libssl routine(ARC4Decryptor class): %s",
-			ERR_error_string(ERR_get_error(), 0));
+    throw DlAbortEx
+      (StringFormat("Exception in libssl routine(ARC4Decryptor class): %s",
+		    ERR_error_string(ERR_get_error(), 0)).str());
   }
 public:
   ARC4Decryptor() {}

+ 4 - 2
src/LibsslARC4Encryptor.h

@@ -38,6 +38,7 @@
 #include "common.h"
 #include "DlAbortEx.h"
 #include "LibsslARC4Context.h"
+#include "StringFormat.h"
 #include <openssl/evp.h>
 #include <openssl/err.h>
 
@@ -49,8 +50,9 @@ private:
 
   void handleError() const
   {
-    throw new DlAbortEx("Exception in libssl routine(ARC4Encryptor class): %s",
-			ERR_error_string(ERR_get_error(), 0));
+    throw DlAbortEx
+      (StringFormat("Exception in libssl routine(ARC4Encryptor class): %s",
+		    ERR_error_string(ERR_get_error(), 0)).str());
   }
 public:
   ARC4Encryptor() {}

+ 14 - 8
src/LibsslDHKeyExchange.h

@@ -37,6 +37,7 @@
 
 #include "common.h"
 #include "DlAbortEx.h"
+#include "StringFormat.h"
 #include <openssl/dh.h>
 #include <openssl/rand.h>
 #include <openssl/err.h>
@@ -60,8 +61,9 @@ private:
 
   void handleError(const std::string& funName) const
   {
-    throw new DlAbortEx("Exception in libssl routine %s(DHKeyExchange class): %s",
-			funName.c_str(), ERR_error_string(ERR_get_error(), 0));
+    throw DlAbortEx
+      (StringFormat("Exception in libssl routine %s(DHKeyExchange class): %s",
+		    funName.c_str(), ERR_error_string(ERR_get_error(), 0)).str());
   }
 public:
   DHKeyExchange():_bnCtx(0),
@@ -120,15 +122,17 @@ public:
   size_t getPublicKey(unsigned char* out, size_t outLength) const
   {
     if(outLength < _keyLength) {
-      throw new DlAbortEx("Insufficient buffer for public key. expect:%u, actual:%u",
-			  _keyLength, outLength);
+      throw DlAbortEx
+	(StringFormat("Insufficient buffer for public key. expect:%u, actual:%u",
+		      _keyLength, outLength).str());
     }
     memset(out, 0, outLength);
     size_t publicKeyBytes = BN_num_bytes(_publicKey);
     size_t offset = _keyLength-publicKeyBytes;
     size_t nwritten = BN_bn2bin(_publicKey, out+offset);
     if(nwritten != publicKeyBytes) {
-      throw new DlAbortEx("BN_bn2bin in DHKeyExchange::getPublicKey, %u bytes written, but %u bytes expected.", nwritten, publicKeyBytes);
+      throw DlAbortEx
+	(StringFormat("BN_bn2bin in DHKeyExchange::getPublicKey, %u bytes written, but %u bytes expected.", nwritten, publicKeyBytes).str());
     }
     return nwritten;
   }
@@ -145,8 +149,9 @@ public:
 		       size_t peerPublicKeyLength) const
   {
     if(outLength < _keyLength) {
-      throw new DlAbortEx("Insufficient buffer for secret. expect:%u, actual:%u",
-			  _keyLength, outLength);
+      throw DlAbortEx
+	(StringFormat("Insufficient buffer for secret. expect:%u, actual:%u",
+		      _keyLength, outLength).str());
     }
 
 
@@ -165,7 +170,8 @@ public:
     size_t nwritten = BN_bn2bin(secret, out+offset);
     BN_free(secret);
     if(nwritten != secretBytes) {
-      throw new DlAbortEx("BN_bn2bin in DHKeyExchange::getPublicKey, %u bytes written, but %u bytes expected.", nwritten, secretBytes);
+      throw DlAbortEx
+	(StringFormat("BN_bn2bin in DHKeyExchange::getPublicKey, %u bytes written, but %u bytes expected.", nwritten, secretBytes).str());
     }
     return nwritten;
   }

+ 5 - 5
src/Logger.h

@@ -45,15 +45,15 @@ class Logger {
 public:
   virtual ~Logger() {}
   virtual void debug(const char* msg, ...) = 0;
-  virtual void debug(const char* msg, Exception* ex, ...) = 0;
+  virtual void debug(const char* msg, Exception& ex, ...) = 0;
   virtual void info(const char* msg, ...) = 0;
-  virtual void info(const char* msg, Exception* ex, ...) = 0;
+  virtual void info(const char* msg, Exception& ex, ...) = 0;
   virtual void notice(const char* msg, ...) = 0;
-  virtual void notice(const char* msg, Exception* ex, ...) = 0;
+  virtual void notice(const char* msg, Exception& ex, ...) = 0;
   virtual void warn(const char* msg, ...) = 0;
-  virtual void warn(const char* msg, Exception* ex, ...) = 0;
+  virtual void warn(const char* msg, Exception& ex, ...) = 0;
   virtual void error(const char*  msg, ...) = 0;
-  virtual void error(const char* msg, Exception* ex, ...) = 0;
+  virtual void error(const char* msg, Exception& ex, ...) = 0;
 
   enum LEVEL {
     DEBUG  = 1 << 0,

+ 17 - 12
src/MSEHandshake.cc

@@ -50,6 +50,7 @@
 #include "BtContext.h"
 #include "prefs.h"
 #include "Option.h"
+#include "StringFormat.h"
 #include <cstring>
 #include <cassert>
 
@@ -92,7 +93,7 @@ MSEHandshake::HANDSHAKE_TYPE MSEHandshake::identifyHandshakeType()
   size_t r = 20-_rbufLength;
   _socket->readData(_rbuf+_rbufLength, r);
   if(r == 0) {
-    throw new DlAbortEx(EX_EOF_FROM_PEER);
+    throw DlAbortEx(EX_EOF_FROM_PEER);
   }
   _rbufLength += r;
   if(_rbufLength < 20) {
@@ -285,7 +286,7 @@ bool MSEHandshake::findInitiatorVCMarker()
   }
   _socket->peekData(_rbuf+_rbufLength, r);
   if(r == 0) {
-    throw new DlAbortEx(EX_EOF_FROM_PEER);
+    throw DlAbortEx(EX_EOF_FROM_PEER);
   }
   // find vc
   {
@@ -293,7 +294,7 @@ bool MSEHandshake::findInitiatorVCMarker()
     std::string vc(&_initiatorVCMarker[0], &_initiatorVCMarker[VC_LENGTH]);
     if((_markerIndex = buf.find(vc)) == std::string::npos) {
       if(616-KEY_LENGTH <= _rbufLength+r) {
-	throw new DlAbortEx("Failed to find VC marker.");
+	throw DlAbortEx("Failed to find VC marker.");
       } else {
 	_socket->readData(_rbuf+_rbufLength, r);
 	_rbufLength += r;
@@ -335,7 +336,8 @@ bool MSEHandshake::receiveInitiatorCryptoSelectAndPadDLength()
       _negotiatedCryptoType = CRYPTO_ARC4;
     }
     if(_negotiatedCryptoType == CRYPTO_NONE) {
-      throw new DlAbortEx("CUID#%d - No supported crypto type selected.", _cuid);
+      throw DlAbortEx
+	(StringFormat("CUID#%d - No supported crypto type selected.", _cuid).str());
     }
   }
   // padD length
@@ -371,7 +373,7 @@ bool MSEHandshake::findReceiverHashMarker()
   }
   _socket->peekData(_rbuf+_rbufLength, r);
   if(r == 0) {
-    throw new DlAbortEx(EX_EOF_FROM_PEER);
+    throw DlAbortEx(EX_EOF_FROM_PEER);
   }
   // find hash('req1', S), S is _secret.
   {
@@ -381,7 +383,7 @@ bool MSEHandshake::findReceiverHashMarker()
     std::string req1(&md[0], &md[sizeof(md)]);
     if((_markerIndex = buf.find(req1)) == std::string::npos) {
       if(628-KEY_LENGTH <= _rbufLength+r) {
-	throw new DlAbortEx("Failed to find hash marker.");
+	throw DlAbortEx("Failed to find hash marker.");
       } else {
 	_socket->readData(_rbuf+_rbufLength, r);
 	_rbufLength += r;
@@ -423,7 +425,7 @@ bool MSEHandshake::receiveReceiverHashAndPadCLength()
     }
   }
   if(btContext.isNull()) {
-    throw new DlAbortEx("Unknown info hash.");
+    throw DlAbortEx("Unknown info hash.");
   }
   initCipher(btContext->getInfoHash());
 
@@ -447,7 +449,8 @@ bool MSEHandshake::receiveReceiverHashAndPadCLength()
       _negotiatedCryptoType = CRYPTO_ARC4;
     }
     if(_negotiatedCryptoType == CRYPTO_NONE) {
-      throw new DlAbortEx("CUID#%d - No supported crypto type provided.", _cuid);
+      throw DlAbortEx
+	(StringFormat("CUID#%d - No supported crypto type provided.", _cuid).str());
     }
   }
   // decrypt PadC length
@@ -518,7 +521,8 @@ uint16_t MSEHandshake::verifyPadLength(const unsigned char* padlenbuf, const std
   uint16_t padLength = decodeLength16(padlenbuf);
   _logger->debug("CUID#%d - len(%s)=%u", _cuid, padName.c_str(), padLength);
   if(padLength > 512) {
-    throw new DlAbortEx("Too large %s length: %u", padName.c_str(), padLength);
+    throw DlAbortEx
+      (StringFormat("Too large %s length: %u", padName.c_str(), padLength).str());
   }
   return padLength;
 }
@@ -529,7 +533,8 @@ void MSEHandshake::verifyVC(const unsigned char* vcbuf)
   unsigned char vc[VC_LENGTH];
   _decryptor->decrypt(vc, sizeof(vc), vcbuf, sizeof(vc));
   if(memcmp(VC, vc, sizeof(VC)) != 0) {
-    throw new DlAbortEx("Invalid VC: %s", Util::toHex(vc, VC_LENGTH).c_str());
+    throw DlAbortEx
+      (StringFormat("Invalid VC: %s", Util::toHex(vc, VC_LENGTH).c_str()).str());
   }
 }
 
@@ -539,7 +544,7 @@ void MSEHandshake::verifyReq1Hash(const unsigned char* req1buf)
   unsigned char md[20];
   createReq1Hash(md);
   if(memcmp(md, req1buf, sizeof(md)) != 0) {
-    throw new DlAbortEx("Invalid req1 hash found.");
+    throw DlAbortEx("Invalid req1 hash found.");
   }
 }
 
@@ -552,7 +557,7 @@ size_t MSEHandshake::receiveNBytes(size_t bytes)
     }
     _socket->readData(_rbuf+_rbufLength, r);
     if(r == 0) {
-      throw new DlAbortEx(EX_EOF_FROM_PEER);
+      throw DlAbortEx(EX_EOF_FROM_PEER);
     }
     _rbufLength += r;
   }

+ 8 - 3
src/MessageDigestHelper.cc

@@ -38,6 +38,7 @@
 #include "message.h"
 #include "DefaultDiskWriter.h"
 #include "Util.h"
+#include "StringFormat.h"
 #include <cerrno>
 
 namespace aria2 {
@@ -88,7 +89,8 @@ std::string MessageDigestHelper::digest(MessageDigestContext* ctx,
   for(uint64_t i = 0; i < iteration; ++i) {
     ssize_t readLength = bs->readData(BUF, BUFSIZE, offset);
     if((size_t)readLength != BUFSIZE) {
-      throw new DlAbortEx(EX_FILE_READ, "n/a", strerror(errno));
+      throw DlAbortEx
+	(StringFormat(EX_FILE_READ, "n/a", strerror(errno)).str());
     }
     ctx->digestUpdate(BUF, readLength);
     offset += readLength;
@@ -96,7 +98,8 @@ std::string MessageDigestHelper::digest(MessageDigestContext* ctx,
   if(tail) {
     ssize_t readLength = bs->readData(BUF, tail, offset);
     if((size_t)readLength != tail) {
-      throw new DlAbortEx(EX_FILE_READ, "n/a", strerror(errno));
+      throw DlAbortEx
+	(StringFormat(EX_FILE_READ, "n/a", strerror(errno)).str());
     }
     ctx->digestUpdate(BUF, readLength);
   }
@@ -125,7 +128,9 @@ void MessageDigestHelper::digest(unsigned char* md, size_t mdLength,
 				 const std::string& algo, const void* data, size_t length)
 {
   if(mdLength < MessageDigestContext::digestLength(algo)) {
-    throw new DlAbortEx("Insufficient space for storing message digest: %d required, but only %d is allocated", MessageDigestContext::digestLength(algo), mdLength);
+    throw DlAbortEx
+      (StringFormat("Insufficient space for storing message digest: %d required, but only %d is allocated",
+		    MessageDigestContext::digestLength(algo), mdLength).str());
   }
   MessageDigestContext ctx;
   ctx.trySetAlgo(algo);

+ 14 - 14
src/MetaFileUtil.cc

@@ -51,18 +51,18 @@ MetaEntry* MetaFileUtil::parseMetaFile(const std::string& file) {
   FILE* fp = fopen(file.c_str(), "r+b");
   try {
     if(!fp) {
-      throw new DlAbortEx("cannot open metainfo file");
+      throw DlAbortEx("cannot open metainfo file");
     }
     if(fread(buf, len, 1, fp) != 1) {
       fclose(fp);
-      throw new DlAbortEx("cannot read metainfo");
+      throw DlAbortEx("cannot read metainfo");
     }
     fclose(fp);
     fp = 0;
     MetaEntry* entry = bdecoding(buf, len);
     delete [] buf;
     return entry;
-  } catch(RecoverableException* ex) {
+  } catch(RecoverableException& ex) {
     delete [] buf;
     if(fp) {
       fclose(fp);
@@ -82,7 +82,7 @@ MetaEntry*
 MetaFileUtil::bdecodingR(const unsigned char** pp, const unsigned char* end)
 {
   if(*pp >= end) {
-    throw new DlAbortEx("Malformed metainfo");
+    throw DlAbortEx("Malformed metainfo");
   }
   MetaEntry* e;
   switch(**pp) {
@@ -108,7 +108,7 @@ Dictionary*
 MetaFileUtil::parseDictionaryTree(const unsigned char** pp, const unsigned char* end)
 {
   if(*pp >= end) {
-    throw new DlAbortEx("Malformed metainfo");
+    throw DlAbortEx("Malformed metainfo");
   }
   Dictionary* dic = new Dictionary();
   try {
@@ -122,7 +122,7 @@ MetaFileUtil::parseDictionaryTree(const unsigned char** pp, const unsigned char*
       dic->put(name, e);
     }
     return dic;
-  } catch(RecoverableException* ex) {
+  } catch(RecoverableException& ex) {
     delete dic;
     throw;
   }
@@ -132,7 +132,7 @@ List*
 MetaFileUtil::parseListTree(const unsigned char** pp, const unsigned char* end)
 {
   if(*pp >= end) {
-    throw new DlAbortEx("Malformed metainfo");
+    throw DlAbortEx("Malformed metainfo");
   }
   List* lis = new List();
   try {
@@ -145,7 +145,7 @@ MetaFileUtil::parseListTree(const unsigned char** pp, const unsigned char* end)
       lis->add(e);
     }
     return lis;
-  } catch(RecoverableException* ex) {
+  } catch(RecoverableException& ex) {
     delete lis;
     throw;
   }
@@ -155,12 +155,12 @@ Data*
 MetaFileUtil::decodeInt(const unsigned char** pp, const unsigned char* end)
 {
   if(*pp >= end) {
-    throw new DlAbortEx(EX_MALFORMED_META_INFO);
+    throw DlAbortEx(EX_MALFORMED_META_INFO);
   }
   unsigned char* endTerm = reinterpret_cast<unsigned char*>(memchr(*pp, 'e', end-*pp));
   // TODO if endTerm is null
   if(!endTerm) {
-    throw new DlAbortEx(EX_MALFORMED_META_INFO);
+    throw DlAbortEx(EX_MALFORMED_META_INFO);
   }
   size_t numSize = endTerm-*pp;
 
@@ -173,12 +173,12 @@ Data*
 MetaFileUtil::decodeWord(const unsigned char** pp, const unsigned char* end)
 {
   if(*pp >= end) {
-    throw new DlAbortEx("Malformed metainfo");
+    throw DlAbortEx("Malformed metainfo");
   }
   unsigned char* delim = reinterpret_cast<unsigned char*>(memchr(*pp, ':', end-*pp));
   // TODO if delim is null
   if(delim == *pp || !delim) {
-    throw new DlAbortEx(EX_MALFORMED_META_INFO);
+    throw DlAbortEx(EX_MALFORMED_META_INFO);
   }
   size_t numSize = delim-*pp;
   unsigned char* temp = new unsigned char[numSize+1];
@@ -189,12 +189,12 @@ MetaFileUtil::decodeWord(const unsigned char** pp, const unsigned char* end)
 				   &endptr, 10);
   if(*endptr != '\0') {
     delete [] temp;
-    throw new DlAbortEx(EX_MALFORMED_META_INFO);
+    throw DlAbortEx(EX_MALFORMED_META_INFO);
   }    
   delete [] temp;
 
   if(delim+1+size > end) {
-    throw new DlAbortEx(EX_MALFORMED_META_INFO);
+    throw DlAbortEx(EX_MALFORMED_META_INFO);
   }
 
   Data* data = new Data(delim+1, size);

+ 1 - 1
src/MetalinkHelper.cc

@@ -72,7 +72,7 @@ std::deque<SharedHandle<MetalinkEntry> >
 MetalinkHelper::query(const SharedHandle<Metalinker>& metalinker, const Option* option)
 {
   if(metalinker->entries.empty()) {
-    throw new DlAbortEx("No file entry found. Probably, the metalink file is not configured properly or broken.");
+    throw DlAbortEx("No file entry found. Probably, the metalink file is not configured properly or broken.");
   }
   std::deque<SharedHandle<MetalinkEntry> > entries =
     metalinker->queryEntry(option->get(PREF_METALINK_VERSION),

+ 1 - 1
src/MetalinkPostDownloadHandler.cc

@@ -66,7 +66,7 @@ MetalinkPostDownloadHandler::getNextRequestGroups(RequestGroup* requestGroup)
     std::deque<SharedHandle<RequestGroup> > rgs = Metalink2RequestGroup(op).generate(diskAdaptor);
     diskAdaptor->closeFile();
     return rgs;
-  } catch(Exception* e) {
+  } catch(Exception& e) {
     diskAdaptor->closeFile();
     throw;
   }

+ 7 - 2
src/MultiDiskAdaptor.cc

@@ -41,6 +41,7 @@
 #include "DefaultDiskWriterFactory.h"
 #include "DlAbortEx.h"
 #include "File.h"
+#include "StringFormat.h"
 
 namespace aria2 {
 
@@ -201,7 +202,9 @@ void MultiDiskAdaptor::writeData(const unsigned char* data, size_t len,
     }
   }
   if(!writing) {
-    throw new DlAbortEx(EX_FILE_OFFSET_OUT_OF_RANGE, Util::itos(offset, true).c_str());
+    throw DlAbortEx
+      (StringFormat(EX_FILE_OFFSET_OUT_OF_RANGE,
+		    Util::itos(offset, true).c_str()).str());
   }
 }
 
@@ -244,7 +247,9 @@ ssize_t MultiDiskAdaptor::readData(unsigned char* data, size_t len, off_t offset
     }
   }
   if(!reading) {
-    throw new DlAbortEx(EX_FILE_OFFSET_OUT_OF_RANGE, Util::itos(offset, true).c_str());
+    throw DlAbortEx
+      (StringFormat(EX_FILE_OFFSET_OUT_OF_RANGE,
+		    Util::itos(offset, true).c_str()).str());
   }
   return totalReadLength;
 }

+ 5 - 2
src/NameMatchOptionHandler.h

@@ -37,6 +37,7 @@
 
 #include "OptionHandler.h"
 #include "DlAbortEx.h"
+#include "StringFormat.h"
 #include <strings.h>
 
 namespace aria2 {
@@ -62,8 +63,10 @@ public:
   {
     try {
       parseArg(option, arg);
-    } catch(Exception* e) {
-      throw new DlAbortEx(e, "Exception occurred while processing option %s", _optName.c_str());
+    } catch(Exception& e) {
+      throw DlAbortEx
+	(StringFormat("Exception occurred while processing option %s",
+		      _optName.c_str()).str(), e);
     }
   }
 };

+ 3 - 2
src/NameResolver.cc

@@ -35,6 +35,7 @@
 #include "NameResolver.h"
 #include "DlAbortEx.h"
 #include "message.h"
+#include "StringFormat.h"
 #include <cstring>
 
 namespace aria2 {
@@ -108,8 +109,8 @@ void NameResolver::resolve(const std::string& hostname)
   struct addrinfo* res;
   int ec;
   if((ec = getaddrinfo(hostname.c_str(), 0, &ai, &res)) != 0) {
-    throw new DlAbortEx(EX_RESOLVE_HOSTNAME,
-			hostname.c_str(), gai_strerror(ec));
+    throw DlAbortEx(StringFormat(EX_RESOLVE_HOSTNAME,
+				 hostname.c_str(), gai_strerror(ec)).str());
   }
   _addr = ((struct sockaddr_in*)res->ai_addr)->sin_addr;
   freeaddrinfo(res);

+ 7 - 3
src/Netrc.cc

@@ -34,6 +34,7 @@
 /* copyright --> */
 #include "Netrc.h"
 #include "RecoverableException.h"
+#include "StringFormat.h"
 #include <fstream>
 #include <algorithm>
 
@@ -45,7 +46,8 @@ std::string Netrc::getRequiredNextToken(std::ifstream& f) const
   if(f >> token) {
     return token;
   } else {
-    throw new RecoverableException("Netrc:parse error. EOF reached where a token expected.");
+    throw RecoverableException
+      ("Netrc:parse error. EOF reached where a token expected.");
   }
 }
 
@@ -66,7 +68,8 @@ void Netrc::parse(const std::string& path)
   std::ifstream f(path.c_str());
   
   if(!f) {
-    throw new RecoverableException("File not found: %s", path.c_str());
+    throw RecoverableException
+      (StringFormat("File not found: %s", path.c_str()).str());
   }
 
   AuthenticatorHandle authenticator;
@@ -81,7 +84,8 @@ void Netrc::parse(const std::string& path)
       authenticator.reset(new DefaultAuthenticator());
     } else {
       if(authenticator.isNull()) {
-	throw new RecoverableException("Netrc:parse error. %s encounterd where 'machine' or 'default' expected.");
+	throw RecoverableException
+	  ("Netrc:parse error. %s encounterd where 'machine' or 'default' expected.");
       }
       if(token == "login") {
 	authenticator->setLogin(getRequiredNextToken(f));

+ 5 - 5
src/NullLogger.h

@@ -42,15 +42,15 @@ public:
   NullLogger() {}
   virtual ~NullLogger() {}
   virtual void debug(const char* msg, ...) const {}
-  virtual void debug(const char* msg, Exception* ex, ...) const {}
+  virtual void debug(const char* msg, Exception& ex, ...) const {}
   virtual void info(const char* msg, ...) const {}
-  virtual void info(const char* msg, Exception* ex, ...) const {}
+  virtual void info(const char* msg, Exception& ex, ...) const {}
   virtual void notice(const char* msg, ...) const {}
-  virtual void notice(const char* msg, Exception* ex, ...) const {}
+  virtual void notice(const char* msg, Exception& ex, ...) const {}
   virtual void warn(const char* msg, ...) const {}
-  virtual void warn(const char* msg, Exception* ex, ...) const {}
+  virtual void warn(const char* msg, Exception& ex, ...) const {}
   virtual void error(const char*  msg, ...) const {}
-  virtual void error(const char* msg, Exception* ex, ...) const {}
+  virtual void error(const char* msg, Exception& ex, ...) const {}
 };
 
 #endif // _D_NULL_LOGGER_H_

+ 21 - 18
src/OptionHandlerImpl.h

@@ -41,6 +41,7 @@
 #include "FatalException.h"
 #include "prefs.h"
 #include "Option.h"
+#include "StringFormat.h"
 #include <utility>
 #include <algorithm>
 
@@ -68,7 +69,7 @@ public:
       option->put(_optName, V_FALSE);
     } else {
       std::string msg = _optName+" "+_("must be either 'true' or 'false'.");
-      throw new FatalException(msg.c_str());
+      throw FatalException(msg);
     }
   }
 };
@@ -89,7 +90,9 @@ public:
       int32_t v = seq.next();
       if(v < _min || _max < v) {
 	std::string msg = _optName+" "+_("must be between %s and %s.");
-	throw new FatalException(msg.c_str(), Util::itos(_min).c_str(), Util::itos(_max).c_str());
+	throw FatalException
+	  (StringFormat(msg.c_str(), Util::itos(_min).c_str(),
+			Util::itos(_max).c_str()).str());
       }
       option->put(_optName, optarg);
     }
@@ -118,18 +121,18 @@ public:
     } else {
       std::string msg = _optName+" ";
       if(_min == -1 && _max != -1) {
-	msg += _("must be smaller than or equal to %s.");
-	throw new FatalException(msg.c_str(), Util::itos(_max).c_str());
+	msg += StringFormat(_("must be smaller than or equal to %s."),
+			    Util::itos(_max).c_str()).str();
       } else if(_min != -1 && _max != -1) {
-	msg += _("must be between %s and %s.");
-	throw new FatalException(msg.c_str(), Util::itos(_min).c_str(), Util::itos(_max).c_str());
+	msg += StringFormat(_("must be between %s and %s."),
+			    Util::itos(_min).c_str(), Util::itos(_max).c_str()).str();
       } else if(_min != -1 && _max == -1) {
-	msg += _("must be greater than or equal to %s.");
-	throw new FatalException(msg.c_str(), Util::itos(_min).c_str());
+	msg += StringFormat(_("must be greater than or equal to %s."),
+			    Util::itos(_min).c_str()).str();
       } else {
 	msg += _("must be a number.");
-	throw new FatalException(msg.c_str());
       }
+      throw FatalException(msg);
     }
   }
 };
@@ -164,18 +167,18 @@ public:
     } else {
       std::string msg = _optName+" ";
       if(_min < 0 && _max >= 0) {
-	msg += _("must be smaller than or equal to %.1f.");
-	throw new FatalException(msg.c_str(), _max);
+	msg += StringFormat(_("must be smaller than or equal to %.1f."),
+			    _max).str();
       } else if(_min >= 0 && _max >= 0) {
-	msg += _("must be between %.1f and %.1f.");
-	throw new FatalException(msg.c_str(), _min, _max);
+	msg += StringFormat(_("must be between %.1f and %.1f."),
+			    _min, _max).str();
       } else if(_min >= 0 && _max < 0) {
-	msg += _("must be greater than or equal to %.1f.");
-	throw new FatalException(msg.c_str(), _min);
+	msg += StringFormat(_("must be greater than or equal to %.1f."),
+			    _min).str();
       } else {
 	msg += _("must be a number.");
-	throw new FatalException(msg.c_str());
       }
+      throw FatalException(msg);
     }
   }
 };
@@ -260,7 +263,7 @@ public:
 	  msg += "'"+*itr+"' ";
 	}
       }
-      throw new FatalException(msg.c_str());
+      throw FatalException(msg);
     } else {
       option->put(_optName, optarg);
     }
@@ -288,7 +291,7 @@ public:
     int32_t port = Util::parseInt(proxy.second);
     if(proxy.first.empty() || proxy.second.empty() ||
        port <= 0 || 65535 < port) {
-      throw new FatalException(_("unrecognized proxy format"));
+      throw FatalException(_("unrecognized proxy format"));
     }
     option->put(_optName, optarg);
     setHostAndPort(option, proxy.first, port);

+ 1 - 1
src/PStringSegment.cc

@@ -51,7 +51,7 @@ void PStringSegment::accept(PStringVisitor* visitor)
 {
   PStringSegmentVisitor* v = dynamic_cast<PStringSegmentVisitor*>(visitor);
   if(!v) {
-    throw new FatalException("Class cast exception");
+    throw FatalException("Class cast exception");
   }
   v->hello(this);
   if(!_next.isNull()) {

+ 6 - 6
src/ParameterizedStringParser.cc

@@ -86,12 +86,12 @@ PStringDatumHandle ParameterizedStringParser::createSelect(const std::string& sr
   ++offset;
   std::string::size_type rightParenIndex = src.find("}", offset);
   if(rightParenIndex == std::string::npos) {
-    throw new FatalException("Missing '}' in the parameterized string.");
+    throw FatalException("Missing '}' in the parameterized string.");
   }
   std::deque<std::string> values;
   Util::slice(values, src.substr(offset, rightParenIndex-offset), ',', true);
   if(values.empty()) {
-    throw new FatalException("Empty {} is not allowed.");
+    throw FatalException("Empty {} is not allowed.");
   }
   offset = rightParenIndex+1;
   PStringDatumHandle next = diggPString(src, offset);
@@ -104,7 +104,7 @@ PStringDatumHandle ParameterizedStringParser::createLoop(const std::string& src,
   ++offset;
   std::string::size_type rightParenIndex = src.find("]", offset);
   if(rightParenIndex == std::string::npos) {
-    throw new FatalException("Missing ']' in the parameterized string.");
+    throw FatalException("Missing ']' in the parameterized string.");
   }
   std::string loopStr = src.substr(offset, rightParenIndex-offset);
   offset = rightParenIndex+1;
@@ -116,13 +116,13 @@ PStringDatumHandle ParameterizedStringParser::createLoop(const std::string& src,
     if(Util::isNumber(stepStr)) {
       step = Util::parseUInt(stepStr);
     } else {
-      throw new FatalException("A step count must be a positive number.");
+      throw FatalException("A step count must be a positive number.");
     }
     loopStr.erase(colonIndex);
   }
   std::pair<std::string, std::string> range = Util::split(loopStr, "-");
   if(range.first == "" || range.second == "") {
-    throw new FatalException("Loop range missing.");
+    throw FatalException("Loop range missing.");
   }
   NumberDecoratorHandle nd;
   unsigned int start;
@@ -140,7 +140,7 @@ PStringDatumHandle ParameterizedStringParser::createLoop(const std::string& src,
     start = Util::alphaToNum(range.first);
     end = Util::alphaToNum(range.second);
   } else {
-    throw new FatalException("Invalid loop range.");
+    throw FatalException("Invalid loop range.");
   }
 
   PStringDatumHandle next(diggPString(src, offset));

+ 4 - 5
src/PeerAbstractCommand.cc

@@ -74,7 +74,7 @@ PeerAbstractCommand::~PeerAbstractCommand() {
 
 bool PeerAbstractCommand::execute() {
   if(exitBeforeExecute()) {
-    onAbort(0);
+    onAbort();
     return true;
   }
   try {
@@ -88,15 +88,14 @@ bool PeerAbstractCommand::execute() {
       checkPoint.reset();
     }
     if(checkPoint.elapsed(timeout)) {
-      throw new DlAbortEx(EX_TIME_OUT);
+      throw DlAbortEx(EX_TIME_OUT);
     }
     return executeInternal();
-  } catch(RecoverableException* err) {
+  } catch(RecoverableException& err) {
     logger->debug(MSG_TORRENT_DOWNLOAD_ABORTED, err, cuid);
     logger->debug(MSG_PEER_BANNED,
 		  cuid, peer->ipaddr.c_str(), peer->port);
-    onAbort(err);
-    delete err;
+    onAbort();
     return prepareForNextPeer(0);
   }
 }

Некоторые файлы не были показаны из-за большого количества измененных файлов