Doctest error al intentar capturar Exception Value error

Os reporto un error de testing. Intento capturar el error de introducir un valor negativo en una raíz cuadrada.

Mi código:

import math   def listaraicescuadradas(Listanumeros):     """      la funcion devuelve una lista con la raiz cuadrada     de los elementos pasados en otra lista por argumentos.     >>> lista = []     >>> for i in [4, -9, 16]:     ... lista.append(i)     >>> listaraicescuadradas(lista)     Traceback (most recent call last):         ...     ValueError: math domain error       """     return [math.sqrt(n) for n in Listanumeros ]  import doctest  doctest.testmod() 

El error que me dispara es:

ValueError: line 12 of the docstring for __main__.listaraicescuadradas has inconsistent leading whitespace: 'ValueError: math domain error 

Gracias adelantadas.

Exception Handling in Class

I have read a few sites on how to handle exceptions and I think I understand it better. Here is how I plan to handle it going forward. I used a lot of the guidelines here,

Is this a sensible to handle it with c++14 as I’m using visual studio 2015. Would it be different with C++17?

#include <iostream> #include <exception> #include <string>  #define THROWFOORTE(what) throw FooRuntimeException(what, __FILE__, __func__, __LINE__) #define THROWFOORE(what) throw FooRangeError(what, __FILE__, __func__, __LINE__)  struct FooRuntimeException     : public std::runtime_error {     FooRuntimeException(const char* what,          const char* file, const char* func, int line)         : runtime_error(std::string(file) +":" +              std::string(func) + ":" + std::to_string(line)              + " " + std::string(what)) {} };  struct FooRangeError     : public std::range_error {     FooRangeError(const char* what,         const char* file, const char* func, int line)         : range_error(std::string(file) + ":" +             std::string(func) + ":" + std::to_string(line)             + " " + std::string(what)) {} };  class Foo { public:     Foo() = default;     ~Foo() {};      void throwRunTimeException()     {         THROWFOORTE("Runtime Error");     }     void throwRangeError()     {         THROWFOORE("Range Error");     } };  void HandleException() {     try { throw; }     catch (const FooRuntimeException &e)     {         std::cerr << e.what() << '\n'; // catches standard error message     }     catch (const FooRangeError&e)     {         std::cerr << e.what() << '\n';; // catches standard error message     }     return; }  int main() {     try     {         auto foo = Foo();         foo.throwRunTimeException();     }     catch (...) {         HandleException();     }        try     {         auto foo = Foo();         foo.throwRangeError();     }     catch (...) {         HandleException();     }      return 0; } 

Break iterations after an exception happens without data loss

I have this code that reads a file and after processing a few lines writes the output to a second file:

num_reads = 7 with open('data.txt') as read_file:     with open('new_data.txt', 'w') as write_file:          while (True):             lines = []             try:       # expect errors if the number of lines in the file are not a multiplication of num_reads                 for i in range(num_reads):                          lines.append(next(read_file))  # when the file finishes an exception occurs here                  #do sutff with the lines (exactly num_reads number of lines)                 processed = " ".join(list(map(lambda x: x.replace("\n", ''), lines)))                 write_file.write(processed + '\n')              except StopIteration:     # here we process the (possibly) insufficent last lines                 #do stuff with the lines (less that  num_reads)                 processed = " ".join(list(map(lambda x: x.replace("\n", ''), lines)))                 write_file.write(processed + '\n')                 break 

Assuming that I wish to do the same processing and writing procedure in both cases (when the number of elements is 7 and when the file finishes sooner). The above code violates DRY principle even if I define a new function and call it once in try block and once in except before break. Any other ordering that I could come up with was either causing an infinite loop or losing the final lines. I appreciate any comments on handling this issue, as it is not limited to this case and I had faced it in other cases as well.

Erro Exception in thread “AWT-EventQueue-0” java.lang.ArrayIndexOutOfBoundsException: -1

Pessoal eu estou fazendo um jogo da velha em java. Criei uma matriz de labels e adicionei evento de clique nessa matriz para que quando eu clicar, adicione um X ou O e mude a cor. Porém fica dando esse erro. se alguem souber o que pode ser. Segue o codigo e o erro.

Eu estou utilizando swing tambem para adicionar botoes e outras funcoes

public class Tabuleiro {

private JFrame frmJogoDaVelha; private JLabel[][] labels = new JLabel[3][3]; private JogoDaVelha jogo; private int numeroJogador=1; private JLabel label; private JButton button; String Simbolo;    /**  * Launch the application.  */ public static void main(String[] args) {     SwingUtilities.invokeLater(new Runnable() {         public void run() {             try {                 Tabuleiro window = new Tabuleiro();                 window.frmJogoDaVelha.setVisible(true);             } catch (Exception e) {                 e.printStackTrace();             }         }     }); } /**  * Create the application.  */ public Tabuleiro() {     initialize(); }  /**  * Initialize the contents of the frame.  */ private void initialize() {     jogo = new JogoDaVelha("joao", "maria");     frmJogoDaVelha = new JFrame();     frmJogoDaVelha.setResizable(false);     frmJogoDaVelha.setTitle("Jogo da Velha");     frmJogoDaVelha.setBounds(100, 100, 444, 436);     frmJogoDaVelha.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     frmJogoDaVelha.getContentPane().setLayout(null);      JPanel panel = new JPanel();     panel.setBorder(new TitledBorder(null, "Tabuleiro", TitledBorder.LEADING, TitledBorder.TOP, null, null));     panel.setBounds(10, 11, 214, 386);     frmJogoDaVelha.getContentPane().add(panel);     panel.setLayout(null);      JPanel panelTabuleiro = new JPanel();     panelTabuleiro.setBounds(26, 37, 155, 192);     panel.add(panelTabuleiro);     panelTabuleiro.setLayout(new GridLayout(3, 3, 10, 10));      JButton btnNovoJogo = new JButton("Novo Jogo");     btnNovoJogo.setBounds(57, 248, 97, 28);     panel.add(btnNovoJogo);      JButton btnNewButton = new JButton("Resultado");     btnNewButton.setBounds(57, 300, 97, 28);     panel.add(btnNewButton);                    for(int i=0; i < 3; i++){                 for(int j=0; j < 3; j++){                           labels[i][j]=new JLabel("");                         frmJogoDaVelha.getContentPane().add(labels[i][j]);                         labels[i][j].setBounds(i*60, j*60, 50, 50); //x,y, width, height - 40x40                         labels[i][j].setBackground(SystemColor.controlHighlight);                         //labels[i][j].setBorder(new LineBorder(new Color(0, 0, 0)));                         labels[i][j].setOpaque(true);                         panelTabuleiro.add(labels[i][j]);                         labels[i][j].addMouseListener(new MouseAdapter(){                            public void mouseClicked(MouseEvent e){                             JLabel b = (JLabel)e.getSource();                             int indicex = b.getX()/40;                             int indicey = b.getY()/40;                              if(numeroJogador==1) {                                 //Simbolo = "X";                                 labels[indicex][indicey].setText("X");                                 labels[indicex][indicey].setBackground(Color.GREEN);                                 labels[indicex][indicey].removeMouseListener(this);                                 labels[indicex][indicey].disable();                             } else {                                 //Simbolo = "O";                                 labels[indicex][indicey].setText("X");                                 labels[indicex][indicey].setBackground(Color.BLUE);                                 labels[indicex][indicey].removeMouseListener(this);                                 labels[indicex][indicey].disable();                             }                              labels[indicex][indicey].setText(Simbolo);                             boolean jogadavalida = jogo.jogarJogador(numeroJogador, indicey, indicex);                               if(numeroJogador==1)                                  numeroJogador=2;                              else numeroJogador=1;                         }                     });                       } //segundo for             }         } 


Exception in thread “AWT-EventQueue-0” java.lang.ArrayIndexOutOfBoundsException: -1

Exception Not Working

I have an observer for sales_order_save_before

<?php      namespace Veratad\AgeVerification\Observer;      use Magento\Framework\ObjectManager\ObjectManager;     use Magento\Framework\Exception\CouldNotSaveException;      class ProcessOrder implements \Magento\Framework\Event\ObserverInterface {        protected $  _veratadCall;       protected $  customerSession;       protected $  _isExcluded;       private $  scopeConfig;        public function __construct(         \Veratad\AgeVerification\Model\Query\Api $  veratadCall,         \Veratad\AgeVerification\Model\Customer\Status $  isExcluded,         \Magento\Customer\Model\Session $  customerSession,         \Magento\Framework\App\Config\ScopeConfigInterface $  scopeConfig       ) {         $  this->_veratadCall = $  veratadCall;         $  this->_isExcluded = $  isExcluded;         $  this->customerSession = $  customerSession;         $  this->scopeConfig = $  scopeConfig;       }          public function execute(\Magento\Framework\Event\Observer $  observer ) {            /*           $  order = $  observer->getEvent()->getOrder();           $  customer = $  this->customerSession->getData();           $  billing = $  order->getBillingAddress()->getData();           $  shipping = $  order->getShippingAddress()->getData();           $  fail_text = $  this->scopeConfig->getValue('settings/content/agematch_fail', \Magento\Store\Model\ScopeInterface::SCOPE_STORE);            $  writer = new \Zend\Log\Writer\Stream(BP . '/var/log/excluded.log');           $  logger = new \Zend\Log\Logger();           $  logger->addWriter($  writer);           //check to see if customer is excluded              $  excluded = $  this->_isExcluded->isExcluded($  customer);             $  logger->info($  excluded);            if(!$  excluded){             $  billing_verified = $  this->_veratadCall->veratadCaller($  billing);             $  logger->info('billing_verified' . $  billing_verified);             if (!$  billing_verified){               $  logger->info("billing not verified");             }         }         */              throw new \Magento\Framework\Exception\CouldNotSaveException(__('You can not place an order because you are not age verified.'));               //$  shipping_verified = $  this->_veratadCall->veratadCaller($  shipping);            //get billing shipping or both setting            //check attempts            //verify           }       } 

The custom message shows when the user is logged in, but throws the generic message if they are a guest. Does anyone know why this is happening?

Unhandled Exception

Ola pessoal, estou fazendo um código em C# usando o Visual Studio com Xamarin, para um leitor de RSS, mas na hora que vou rodar o programa, ele da esse erro, já pesquisei o que poderia ser, mas não consegui encontrar um meio de resolver, se alguém puder ajudar, agradeço

Abaixo segue o código do HTTPDataHandler.

public class HTTPDataHandler {     static string stream = null;      public String GetHTTPData(string urlString)     {         try         {             URL url = new URL(urlString);             using (var urlConnection = (HttpURLConnection)url.OpenConnection())             {                 if(urlConnection.ResponseCode == HttpStatus.Ok)                 {                     BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.InputStream));                     StringBuilder sb = new StringBuilder();                     String line;                     while((line = reader.ReadLine()) != null)                     {                         sb.Append(line);                         stream = sb.ToString();                         urlConnection.Disconnect();                     }                 }             }         }         catch(Exception ex)         {          }         return stream;     } } 

Correct way to raise exception on API’s that return nothing?

We are having a web application where we read data from an XML which returns NONE or [] when there is no data. I would like to raise an exception when that happens because my code needs it and I can give a corrective action as well. We plan to use that pattern across the application.

However, what is the preferred way to raise it?

a = getElements("Tag") if not a:     raise Exception("Tag not found") return a[0] 


a = getElements("Tag") try:     a[0] except NoneType, IndexError:     raise Exception("Tag not found") 

I like the first one because it seems to be closer to the problem, however the second one is better in terms of performance because we don’t need the additional check. Is there a preferred way?

Exception #0 (BadMethodCallException): Missing required argument $variablePluginConfigProvider of Magento\Cms\Model\Wysiwyg\CompositeConfigProvider

![Exception #0 (BadMethodCallException): Missing required argument $ variablePluginConfigProvider of Magento\Cms\Model\Wysiwyg\CompositeConfigProvider. ]1