c++ – Why I couldn’t handle an exception thrown from a destructor outside of it?

I’ve read in C++ primer 5th edition ch18 on Exception Handling that a destructor usually should not throw an exception like STL containers and if it should, that thrown expression should be wrapped in a try-catch block (a catch must handle that exception).

  • I’ve tried this for understanding purpose:

      struct Foo{
          Foo(){
              std::cout << "Foo()n";
          }
          ~Foo(){
              std::cout << "~Foo()n";
              throw "exception thrown from Foo::~Foo()n";
              std::cout << "Back in Foo::~Foo()n";
          }
      };
    
    
      int main(){
    
          try{
              Foo f{};
              Foo* pFoo = new Foo{};
              delete pFoo; // normally exception caught here nad handled by the following catch
          }
          catch(char const* const& cp){
              std::cout << cp << 'n';
          }
    
          std::cout << 'n';
      }
    
  • IMHO Foo‘s Destructor should not here throw that exception because a handler outside that Destructor can never catch that exception; because destructor is invoked whenever an object goes out of scope and a try-catch block is always inside a block, in other words the destructor is called after a try-catch blcok.

  • But as we know we can call a destructor prematurely for example calling it explicitly or deleting a pointer of a class/struct type that points to a valid dynamic memory. So in this case we can call that destructor inside a try-block which normally can be handled by the corresponding handler.

  • But my program always calls terminate() (as a sign of unhandled exception) and I get the warning:

warning: throw will always call 'terminate' (-wterminate).

  • AS you can see I am invoking the Foo destructor inside try-block in main: delete Foo. The same I can do if I wrote: f.~Foo();.

  • So can someone explain the reason behind that? Thank you!

design – Handling same exception thrown by different methods

This depends entirely how you will handle the errors.

  • If you can’t handle the errors meaningfully, don’t.
  • If your functions raise errors that can be meaningfully handled, then the errors should be meaningful.

Often, no error handling is the most appropriate approach. In many contexts, just letting errors propagate can be totally acceptable.

Sometimes, a broad error category like OSError is sufficient to understand what has gone wrong and how your code can recover. Depending on context, inspecting the error’s errno could yield further information. Such a strategy might be suitable for a function that wraps a lower-level function. But this has the implication that the other code needs to understand the OSError appropriately.

But in general, there is no good way around defining custom exception types that communicate the problem in a manner that is suitable in the context of your business logic. If your code needs to treat a failed read differently from a missing folder, your code should have a clear representation of these concepts. Any program has some kind of data model. We can use classes to structure this model, and to give names to certain concepts. Exceptions are a part of this model just like other classes.


While the above is nice theory, the most practical approach might be to maintain extra state variables that let us understand where the exception originated from:

checkpoint = 'start'
try:
    someMethod()  # raises OSError
    checkpoint = 'inner'
    someOtherMethod()  # raises OSError
except OSError as ex:
    if checkpoint == 'start':
      handle_this(ex)
    else:
      handle_that(ex)

A similar idea would be to inspect the exceptions stack trace to determine which function caused it…

While such techniques are not generally a good idea because such state or such dependency on internal functions can make the code massively more complex to maintain, it can be appropriate on a small scale, e.g. scripts or in code that does not depend on other modules.

exception – Facing error in one of the selenium assignment I was practicing

Below is the code I wrote in Java to perform a test which involves switching to windows handles.

package com.Practice;

import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Assignment4 {

    public static void main(String() args) {
        System.setProperty("webdriver.chrome.driver", "C:\Users\vikas\Downloads\chromedriver.exe");

        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.get("http://the-internet.herokuapp.com/");
        driver.findElement(By.xpath("(//div(@id='content')/ul)/li(33)")).click();
        driver.findElement(By.cssSelector("a(href*='windows')")).click();
        Set<String> windows = driver.getWindowHandles();
        Iterator<String> it = windows.iterator();
        String parentId = it.next();
        String childId = it.next();
        driver.switchTo().window(childId);
        System.out.println(driver.findElement(By.xpath("//h3(contains(text(),'New Window'))")).getText());
        driver.switchTo().window(parentId);
        System.out.println(driver.findElement(By.xpath("//div(@id='content')/div/h3")).getText());
    }

}

To the best of my knowledge I assume this code is correct but still I am facing error. I am facing no such element exception.

Exception in thread “main” java.util.NoSuchElementException
at java.base/java.util.LinkedHashMap$LinkedHashIterator.nextNode(LinkedHashMap.java:760)
at java.base/java.util.LinkedHashMap$LinkedKeyIterator.next(LinkedHashMap.java:780)
at com.Practice.Assignment4.main(Assignment4.java:22)

magento2 – After update Magento 2.3.5 to 2.4.2 on all category pages error: Exception #0 (RuntimeException): Catalog Layer has been already created. How fix?

After updating the version, I started getting on all category pages this error: Exception #0 (RuntimeException): Catalog Layer has been already created

enter image description here

This is error in: vendor/magento/module-catalog/Model/Layer/Resolver.php

 /**
 * Create Catalog Layer by specified type
 *
 * @param string $layerType
 * @return void
 */
public function create($layerType)
{
    if (isset($this->layer)) {
        throw new RuntimeException('Catalog Layer has been already created');
    }
    if (!isset($this->layersPool($layerType))) {
        throw new InvalidArgumentException($layerType . ' does not belong to any registered layer');
    }
    $this->layer = $this->objectManager->create($this->layersPool($layerType));
}

$layerType = ‘category’ from vendor/magento/module-catalog/Controller/Category/View.php

 /**
 * Category view action
 *
 * @throws NoSuchEntityException
 */
public function execute()
{
    $result = null;

    if ($this->_request->getParam(ActionInterface::PARAM_NAME_URL_ENCODED)) {
        return $this->resultRedirectFactory->create()->setUrl($this->_redirect->getRedirectUrl());
    }
    $category = $this->_initCategory();
    if ($category) {
        $this->layerResolver->create(Resolver::CATALOG_LAYER_CATEGORY);
        $settings = $this->_catalogDesign->getDesignSettings($category);

        // apply custom design
        if ($settings->getCustomDesign()) {
            $this->_catalogDesign->applyCustomDesign($settings->getCustomDesign());
        }

        $this->_catalogSession->setLastViewedCategoryId($category->getId());

        $page = $this->resultPageFactory->create();
        // apply custom layout (page) template once the blocks are generated
        if ($settings->getPageLayout()) {
            $page->getConfig()->setPageLayout($settings->getPageLayout());
        }

        $pageType = $this->getPageType($category);

        if (!$category->hasChildren()) {
            // Two levels removed from parent.  Need to add default page type.
            $parentPageType = strtok($pageType, '_');
            $page->addPageLayoutHandles(('type' => $parentPageType), null, false);
        }
        $page->addPageLayoutHandles(('type' => $pageType), null, false);
        $page->addPageLayoutHandles(('displaymode' => strtolower($category->getDisplayMode())), null, false);
        $page->addPageLayoutHandles(('id' => $category->getId()));

        // apply custom layout update once layout is loaded
        $this->applyLayoutUpdates($page, $settings);

        $page->getConfig()->addBodyClass('page-products')
            ->addBodyClass('categorypath-' . $this->categoryUrlPathGenerator->getUrlPath($category))
            ->addBodyClass('category-' . $category->getUrlKey());

        return $page;
    } elseif (!$this->getResponse()->isRedirect()) {
        $result = $this->resultForwardFactory->create()->forward('noroute');
    }
    return $result;
}

But i can’t found where loaded Category Layer too. I check this issue in Google and i found this issue, but without answer.
I have Amasty modules like Amasty_Shopby and required modules for him and after disabling this modules i am not getting this error. How can I fix this error without turning off these modules?

Please, help with this issue! Thanks!

java – Spring boot 2.3.3.RELEASE project fails build with exception “org.gradle.api.plugins.UnknownPluginException” in gradle version 5.6.3

my gradle version is 5.6.3.

while I run a spring boot project of 2.3.3.RELEASE with ‘gradle clean build’ it shows me following error:

Plugin (id: 'org.springframework.boot', version: '2.3.3.RELEASE') was not found in any of the following sources:

- Gradle Core Plugins (plugin is not in 'org.gradle' namespace)
- Plugin Repositories (could not resolve plugin artifact 'org.springframework.boot:org.springframework.boot.gradle.plugin:2.3.3.RELEASE')
  Searched in the following repositories:
    Gradle Central Plugin Repository

Exception when calling Postgresql function returning a local numeric from C#

I wrote a Postgresql function to insert a row and return the value generated from the identity column. I receive the following exception when trying to call it from C#.

Npgsql.PostgresException: ‘42601: query has no destination for result data’

I have looked around for an answer, and it seems ExecuteScalar has worked for others, but in all the examples I’ve seen, it’s usually when using RETURN QUERY, not a local variable. What am I missing?

Here is the function:

CREATE OR REPLACE FUNCTION public.func_insert_item(_name character varying)
 RETURNS BIGINT
 LANGUAGE plpgsql
AS $function$
DECLARE
    _item_id BIGINT;
BEGIN

    INSERT INTO public.items
    (
        name
    )
    VALUES
    (
        _name
    )
    RETURNING _item_id;
    
    RETURN _item_id;
END;
$function$

Here is the C#:


        static NpgsqlParameter CreateParameter(string name, ParameterDirection direction, string value)
        {
            var parameter = new NpgsqlParameter(name, NpgsqlTypes.NpgsqlDbType.Varchar, value.Length);
            parameter.Direction = direction;
            parameter.Value = value;

            return parameter;
        }

        static void Main(string() args)
        {
            using var connection = new NpgsqlConnection(connectionString.ToString());
            connection.Open();
            
            using var command = new NpgsqlCommand("func_insert_item", connection);
            command.CommandType = CommandType.StoredProcedure;

            command.Parameters.Add(CreateParameter("_name", ParameterDirection.Input, name));

            object itemId = command.ExecuteScalar();
        }

8 – how throw a custom exception in JSONAPI?

In D8 i’m trying to throw custom exceptions for extra validations that i need to do before the content is saved in my custom entity, but when i do the validations in the presave method and throw a normal Exception:

public function preSave(EntityStorageInterface $storage) { 
  throw new Exception("The content is duplicated", 409);
}

The response of JSONAPI is code 500 Internal Server Error and the response:

{
"jsonapi": {
    "version": "1.0",
    "meta": {
        "links": {
            "self": {
                "href": "http://jsonapi.org/format/1.0/"
            }
        }
    }
},
"errors": (
    {
        "title": "Internal Server Error",
        "status": "500",
        "detail": "The content is duplicated",
        "links": {
            "via": {
                "href": "http://site.docksal/jsonapi/content_entity/content_entity"
            },
            "info": {
                "href": "http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.1"
            }
        }
    }
)

}

how can i control de error Code, title, status and detail.

Kali LInux hashcat Hash-value exception No hashes loaded. Error

idk what had just happened with the hash cat …I am trying to crack a zip file …Yeah Zip file…Now I got the hash from the John The Ripper..And i just save the hash in a txt file…
now i want to crack the hash with hash cat …. I specified everything line -a -0 -m also the wordlist file… as i press enter i get this error
Hashfile ‘PLEASE’ on line 1 ($pkzip…81da44e2d81b012284228a*$/pkzip2$): Hash-value exception
No hashes loaded.

Started: Tue Feb 9 14:59:37 2021
Stopped: Tue Feb 9 14:59:37 2021
Can someone plase help me in solving this error?