Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2024-07-28 22:48:30

0001 #include "FWCore/Utilities/interface/ExceptionCollector.h"
0002 #include "FWCore/Utilities/interface/Exception.h"
0003 #include "FWCore/Utilities/interface/ConvertException.h"
0004 
0005 #include <exception>
0006 #include <memory>
0007 
0008 namespace edm {
0009 
0010   class MultipleException : public cms::Exception {
0011   public:
0012     MultipleException(int iReturnValue, std::string const& iMessage)
0013         : cms::Exception("MultipleExceptions", iMessage), returnValue_(iReturnValue) {}
0014 
0015     Exception* clone() const override { return new MultipleException(*this); }
0016 
0017   private:
0018     int returnCode_() const override { return returnValue_; }
0019 
0020     int returnValue_;
0021   };
0022 
0023   ExceptionCollector::ExceptionCollector(std::string const& initialMessage)
0024       : initialMessage_(initialMessage), firstException_(), accumulatedExceptions_(), nExceptions_(0) {}
0025 
0026   ExceptionCollector::~ExceptionCollector() {}
0027 
0028   bool ExceptionCollector::hasThrown() const { return nExceptions_ > 0; }
0029 
0030   void ExceptionCollector::rethrow() const {
0031     if (nExceptions_ == 1) {
0032       firstException_->raise();
0033     } else if (nExceptions_ > 1) {
0034       accumulatedExceptions_->raise();
0035     }
0036   }
0037 
0038   void ExceptionCollector::call(std::function<void(void)> f) {
0039     try {
0040       convertException::wrap([&f]() { f(); });
0041     } catch (cms::Exception const& ex) {
0042       ++nExceptions_;
0043       if (nExceptions_ == 1) {
0044         firstException_.reset(ex.clone());
0045         accumulatedExceptions_ = std::make_unique<MultipleException>(ex.returnCode(), initialMessage_);
0046       }
0047       *accumulatedExceptions_ << "----- Exception " << nExceptions_ << " -----"
0048                               << "\n"
0049                               << ex.explainSelf();
0050     }
0051   }
0052 
0053   void ExceptionCollector::addException(cms::Exception const& exception) {
0054     ++nExceptions_;
0055     if (nExceptions_ == 1) {
0056       firstException_.reset(exception.clone());
0057       accumulatedExceptions_ = std::make_unique<MultipleException>(exception.returnCode(), initialMessage_);
0058     }
0059     *accumulatedExceptions_ << "----- Exception " << nExceptions_ << " -----"
0060                             << "\n"
0061                             << exception.explainSelf();
0062   }
0063 }  // namespace edm