Exception handling - JMS

I have number of types exceptions being thrown in my application. Of them JMS, Database, user-defined and others. I am using MessageListener to receive messages from a queue. If I use ExceptionListener, I can only handle JMS exceptions in a class implementing ExceptionListener. I would like to handle all the exceptions together. Do you suggest a best way for this
thanks
Shiva

I would have thought that you could build a class that not only implements javax.jms.ExceptionListener, but that could also be used to handle any other exceptions from other places in your code. You could add bean style methods to pass syncronous exceptions to the class as well as implementing any other ascynchronous exception handlers from your database or whatever.
E.g.
public class ExceptionHandler implements javax.jms.ExceptionListener, anyotherexceptionlistenerstyleinterface
public void handleException (Exception e)
public void onException (javax.jms.JMSException e)
Hope this helps a little,
Tom Jenkinson
Arjuna Technologies Limited

Similar Messages

  • Exception Handling (in Mapping) with out using BPM

    Hello All,
    We are on SP17. I have a simple flow involving XI
    JMS -> XI (Message Mapping -> XSL Mapping)  -> Mail
    I would like to send an email if there is an exception in any of the mapping. But I <b>don't want to use a BPM</b> for this exception handling. How can I do it?
    Thanks
    Abinash

    Hi Abinash,
    yes you can! See these..
    /people/alessandro.guarneri/blog/2006/01/26/throwing-smart-exceptions-in-xi-graphical-mapping
    /people/sap.user72/blog/2005/02/23/raising-exceptions-in-sap-xi-mapping
    All the best!
    cheers,
    Prashanth
    P.S Please mark helpful answers

  • How to notify the exceptions in JMS sychronous request-response processing?

              Hi All,
              Pl. help me with ur expertise in the foll. scenario we are facing.
              Scenario:
              I have a requirement where I need to notify the exceptions to my client while
              the client request's are processed asynchronously and my client is waiting in
              synchronous for the response.
              The client is sending a message to one queue (QueueA) and waiting for response
              in another queue (QueueB). The message from "QueueA" is picked up by a MDB listening
              to "QueueA" and it throws an exception while processing some "business logic".
              In this case how do I notify to my client who is waiting in another queue. i.e.
              "QueueB" that there is an exception occurred while processing the business logic.
              I am using JMSCorrelationID to uniquely identify a response for a request sent
              by the client.
              What are the possible options to handle exceptions in JMS for an implementation
              like the one mentioned above.
              Any comments/feedback/pointers will be REALLY REALLY appreciated.
              Tks and regds
              C R Baradwaj
              

              Raghuram Bharadwaj C wrote:
              > Tom,
              >
              > Once again thanks a lot for your prompt response!
              >
              > Yes, A Knows how many downstream queues are involved.
              >
              > For unanticipated multiple responses
              >
              > If I do a select for update in all the MDB's listening to "QueueB/QueueC/QueueD",
              > only one response message will be sent to the "ResponseQ".
              Does this run the risk of serializing the database access? If
              B/C/D have no messages so that a new operation causes all
              three to fire at once, will they end up serializing on their
              respective selectForUpdate calls, losing parallelism?
              >
              > The response from all the datasource(s) are updated in the database by the MDB.
              > The MDB which updates the database last will consolidate all the response(s) and
              > send one final response to the "ResponseQ".
              >
              > This will be picked up the client who is waiting in the "ResponseQ". There wont
              > be multiple message(s) placed in the "ResponseQ".
              >
              > In this situation, How do I handle exceptions that occur in downstream MDB's?
              Use multiple responses. MDB's send error message on response.
              Or have failing MDB put an error message in the database table, so
              that the final responder can read the error message?
              >
              > Many Thanks in Advance,
              > C R Baradwaj
              >
              >
              >
              >
              >
              >
              >
              >
              >
              >
              > Tom Barnes <[email protected]> wrote:
              >
              >>
              >>Raghuram Bharadwaj C wrote:
              >>
              >>>Thanks tom for your support!
              >>>
              >>>Let me explain more about the problem.
              >>>
              >>>Scenario
              >>>========
              >>>Lets take a simplest case where the client is sending a message to
              >>
              >>"QueueA" and
              >>
              >>>he is now waiting for a response in the "ResponseQ"
              >>>
              >>>The MDB listening to "QueueA" wakes up and split the message(s) into
              >>
              >>three and
              >>
              >>>passing it to the next layer of datasource specific queue(s). The queue(s)
              >>
              >>are
              >>
              >>>"QueueB", "QueueC" and "QueueD".
              >>>
              >>>The MDB listening to the datasource specific queue(s) picks up the
              >>
              >>datasource
              >>
              >>>request sends it to the datasource and gets the response back from
              >>
              >>the datasource.
              >>
              >>>The MDB also updates a table in the database with the response. The
              >>
              >>MDB also check(s)
              >>
              >>>after updating the database to see all response(s) from all the datasource(s)
              >>>are reached. If yes, one of the MDB also sends a acknowledgement to
              >>
              >>the "ResponseQ".
              >>
              >>>
              >>>The client listening to the "ResponseQ" gets the acknowledgement and
              >>
              >>hit the database
              >>
              >>>to collect all the response(s) from all the datasource(s). These response(s)
              >>
              >>are
              >>
              >>>formatted and sent a response to the client. We have also created uniqueid
              >>
              >>for
              >>
              >>>identifying each request. This uniqueid is set in the JMSCorrelationID.
              >>
              >>The client
              >>
              >>>uses the uniqueid to collect all the response(s) for the request he
              >>
              >>had sent.
              >>
              >>>Problem
              >>>=======
              >>>If an error/exception occurred in a one of the MDB which is listening
              >>
              >>to QueueB/QueueC/QueueD.
              >>
              >>>How do we handle this?
              >>>
              >>>Please let me know all the possibilities that you would have done in
              >>
              >>this case.
              >>
              >>>
              >>Does A know how many downstream queues are involved? As part of its
              >>transaction it can send a message to the responseQ stating which
              >>queues to expect responses from. The client gets this message
              >>and knows that it must get responses from all of B, C, D, etc.
              >>before assuming success. On a failure, B, C, D, etc. can send
              >>an error message back to the response Q, or the client can
              >>simply timeout.
              >>
              >>This way there are no race conditions
              >>involving unanticipated multiple responses or missing
              >>responses, which I think the
              >>algorithm you mention above can create.
              >>Assuming just B and C (no D):
              >> B detects C is done by checking the DB
              >> C detects B is done by checking the DB **at the same time**
              >> Two response messages get sent
              >> - or -
              >> B finishes detects C not done, and sends no message.
              >> C finishes, B is finished but not reflected in DB yet, sends
              >> no message.
              >>
              >>NOTE: Be aware that when a transaction commits, different
              >>resources can response "faster" than others. The transaction
              >>monitor has no control over this. So, if as part of the
              >>same commit, a database insert and a queue insert is
              >>performed, it is possible for a consumer to receive the
              >>new message BEFORE the new database insert actually completes.
              >>
              >>
              >>>
              >>>Many Thanks in Advance,
              >>>
              >>>C R Baradwaj
              >>>
              >>>
              >>>
              >>>
              >>>
              >>>
              >>>
              >>>
              >>>Assuming that
              >>>
              >>>Tom Barnes <[email protected]> wrote:
              >>>
              >>>
              >>>>One approach is to send an "error" message to QB that uses
              >>>>the JMSCorrelationID the consumer is expecting. This will
              >>>>wake up the consumer, and the consumer can react to
              >>>>the error as needed.
              >>>>
              >>>>Another is to use two asynchronous listeners, one on the
              >>>>response queue, and one on a temporary (client created)
              >>>>queue. On error detection the MDB can send error messages
              >>>>to the temporary queue.
              >>>>
              >>>>You may want to skim the book "Professional JMS" - as I
              >>>>recall, it contains a section on queueing design patterns.
              >>>>
              >>>>Tom
              >>>>
              >>>>Raghuram Bharadwaj C wrote:
              >>>>
              >>>>
              >>>>
              >>>>>Hi All,
              >>>>>
              >>>>>Pl. help me with ur expertise in the foll. scenario we are facing.
              >>>>>
              >>>>>Scenario:
              >>>>>I have a requirement where I need to notify the exceptions to my client
              >>>>
              >>>>while
              >>>>
              >>>>
              >>>>>the client request's are processed asynchronously and my client is
              >>>>
              >>>>waiting in
              >>>>
              >>>>
              >>>>>synchronous for the response.
              >>>>>
              >>>>>The client is sending a message to one queue (QueueA) and waiting
              >>
              >>for
              >>
              >>>>response
              >>>>
              >>>>
              >>>>>in another queue (QueueB). The message from "QueueA" is picked up
              >>
              >>by
              >>
              >>>>a MDB listening
              >>>>
              >>>>
              >>>>>to "QueueA" and it throws an exception while processing some "business
              >>>>
              >>>>logic".
              >>>>
              >>>>
              >>>>>In this case how do I notify to my client who is waiting in another
              >>>>
              >>>>queue. i.e.
              >>>>
              >>>>
              >>>>>"QueueB" that there is an exception occurred while processing the
              >>
              >>business
              >>
              >>>>logic.
              >>>>
              >>>>
              >>>>>I am using JMSCorrelationID to uniquely identify a response for a
              >>
              >>request
              >>
              >>>>sent
              >>>>
              >>>>
              >>>>>by the client.
              >>>>>
              >>>>>What are the possible options to handle exceptions in JMS for an implementation
              >>>>>like the one mentioned above.
              >>>>>
              >>>>>Any comments/feedback/pointers will be REALLY REALLY appreciated.
              >>>>>
              >>>>>Tks and regds
              >>>>>C R Baradwaj
              >>>>
              >
              

  • B2B Exception handling

    Hi,
    Implementing exception handling part for B2B and the version using is 11g.
    I am implementing exception handling by using JMS queue "B2B_IN_QUEUE".
    If message is getting error out then B2B producing error message into "B2B_IN_QUEUE".
    Checked in server and "B2B_IN_QUEUE" consist the error message.
    In BPEL I am consuming the message. But the instance is not getting created for the message available in "B2B_IN_QUEUE".
    In Jms Adapter configuration wizard not provided the option for defining consumer type as "B2BErroruser". Due to consumer type is undefined thinking bpel is not intiating itself by consuming the error message available in "B2B_IN_QUEUE".
    I tried by providing message property "MSG_TYPE" value as '3' also.
    But still Bpel instance is not creating...
    Please tell me is required to set any other message properties to make bpel to consume the message.
    Thanks&Regards,
    Sridhar.Rachumallu
    Edited by: sridhar.rachumallu on Nov 30, 2010 10:31 AM
    Edited by: sridhar.rachumallu on Nov 30, 2010 10:40 AM
    Edited by: sridhar.rachumallu on Nov 30, 2010 8:47 PM

    Hi Anuj,
    First of all check whether there is any consumer on B2B_IN_Queue or not? You may check it on weblogic admin console.
    I am checking for the consumers information in Monitor tab of B2B_IN_Queue and noticed the below information
    Consumers Current : 0
    Consumers High : 1
    Consumers Total : 1
    Messages Current : 3
    Messages Pending : 0
    Messages Total : 3
    Messages High : 3
    After deployed the BPEL process the value of 'Consumers Current' not updating to 1 from 0.
    Values of Consumers Total and Consumers Current not changing after deploying the process or after un deploying the bpel process.
    Can you please tell me what is difference between Consumers Total and Consumers Current?
    If the path i am using for getting consumers information of B2B_IN_Queue is wrong please suggest correct path in the admin console.
    Thanks&Regards,
    Sridhar.Rachumallu
    Edited by: sridhar.rachumallu on Dec 1, 2010 1:41 AM
    Edited by: sridhar.rachumallu on Dec 1, 2010 1:47 AM
    Edited by: sridhar.rachumallu on Dec 1, 2010 2:53 AM

  • ESB Exception handling

    Dave,
    In your Advanced Architecture presentation you mentioned about default and custom error handlers for non transactional end points. And you mentiond JMS:// and BPEL:// handlers as an example. So my question is how to configure this? I assume this involves editing ESB service files. Any documentation in this regard is appreciated. I know BPEL supports this via inbound activation specs but not sure about ESB.
    By transactional you mean Asynch invocations, right? If I invoke a BPEL either via SOAP or internal Java binding, can I still use the exception handling for a Asynch invocation?
    Thanks in advance.
    Regards,
    Rajesh

    Hi Dave,
    I checked this document yesterday, it contained 18 pages.
    Some great info in the additional 7 pages, just in time as well: at a customer site we are hitting bug 5547165, the rejected messages being empty. I checked the rejection handlers for BPEL and was investigating how these could be used in case of ESB. Seems you have provided the answer.
    Any chance a fix for the bug mentioned here is in the 10.1.3.3 patch set?
    One more thing: by default the rejected messages for ESB are written to file system, in a directory below the 'home' OC4J instance. Could this be turned into a configurable space in a next release?
    Thanks and best regards, Sjoerd

  • Handling JMS destination limits

              Hello
              I am trying to figure out the best way to handle the maximum number of messages
              or maximum bytes related errors in a WLS 7.1 JMS destination. I initially expected
              that if the destination got full, WLS would retry using the redelivery mechanism
              and then eventually post it to a 'error' destination. But aparrently it does not
              work that way. I instead get back an exception(weblogic.jms.common.ResourceAllocationException)
              in my code.
              How does one normally handle such conditions?
              Thanks
              

    Hi Ramdas,
              Answers in-line.
              Ramdas Hegde wrote:
              > Hello
              >
              > I am trying to figure out the best way to handle the maximum number of messages
              > or maximum bytes related errors in a WLS 7.1 JMS destination. I initially expected
              > that if the destination got full, WLS would retry using the redelivery mechanism
              > and then eventually post it to a 'error' destination. But aparrently it does not
              > work that way. I instead get back an exception(weblogic.jms.common.ResourceAllocationException)
              > in my code.
              > How does one normally handle such conditions?
              At this point the sender should pause a little before trying again, to
              avoid pounding the CPU with failed send requests.
              If you haven't already, you should probably turn on message paging
              to allow the JMS server to handle more messages.
              Note that 7.0 has a feature which can be used to artificially slow
              down active senders under certain conditions, in order to help
              prevent quota failures. It is called "Sender Throttling" and is
              configurable on the connection factory.
              Note that 8.1 has a feature which cause the sender to block waiting
              for quota conditions to clear for a configurable amount of
              time (by default 15 ms).
              You may find it helpful to read the "WebLogic JMS Performance Guide"
              white-paper on dev2dev.bea.com. The last section outlines
              some other approaches to handling overflow conditions.
              >
              > Thanks
              Your Welcome
              Tom, BEA
              

  • A RunTime exception in JMS

              I am using weblogic server 6.0 service pack 2.
              The problem is in runtime exception in JMS.
              Here is an exception I am getting:
              java.lang.RuntimeException: Client possibly malfunctioning as RuntimeException thrown
              from the onMessage routine of the client
              at weblogic.jms.client.JMSSession.onMessage(JMSSession.java:1938)
              at weblogic.jms.client.JMSSession.run(JMSSession.java:881)
              at weblogic.jms.backend.BEServerSession.execute(BEServerSession.java:83)
              at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:137)
              at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:120)
              This occurs in the line
              >bsender = bsession.createSender(bqueue);
              of the class, in the onMessage method.
              What is the reason for the exception? What can be done to fix it? I just need to
              process several messages in parallel.
              I have a startup class RateQuoteJMSResponse, that calls JMS.
              This happens only when I have a message listeners pool. When I did not use the pool,
              it worked OK. But I want to allow processing messages in parallel, and as I understand,
              there is no other option except using ServerSessionPool.
              When I tried to do that just with QueueReceiver, it worked OK:
                        qreceiver = qsession.createReceiver (queue);
                        qreceiver.setMessageListener (this);
                        qcon.start();
              However, that way messages were not processed in parallel.
              Here is my code:
              package com.bbb.object.jms;
              import java.io.*;
              import java.util.*;
              import javax.jts.*;
              import javax.naming.*;
              import javax.jms.*;
              import com.bbb.object.*;
              import com.bbb.object.RateQuote.*;
              import org.apache.crimson.tree.*;
              import org.w3c.dom.*;
              import weblogic.jms.extensions.JMSHelper;
              import weblogic.jms.ServerSessionPoolFactory;
              public class RateQuoteJMSResponse implements MessageListener
                   private final static String JNDI_FACTORY="weblogic.jndi.WLInitialContextFactory";
                   private final static String JMS_FACTORY="weblogic.closs.jms.QueueConnectionFactory";
                   private final static String SESSION_POOL_FACTORY="weblogic.jms.ServerSessionPoolFactory:ClossJMSServer";
                   private final static int ALL_OCCUPIED = -1;
                   private static REServer servers [];
                   private static REServersThrottle throttle;
                   private QueueConnectionFactory qconFactory;
                   private QueueConnection qcon;
                   private QueueSession qsession;
                   private QueueSession bsession;
                   //private QueueReceiver qreceiver;
                   private QueueSender bsender = null;
                   private Queue queue;
                   private Queue bqueue;
                   private ServerSessionPoolFactory sessionPoolFactory;
                   private ServerSessionPool sessionPool;
                   private ConnectionConsumer consumer;
                   private int findUnoccupiedServer ()
                        for (int ii = 0; ii < servers.length; ii++)
                             if (servers[ii].isActive () && !servers [ii].isOccupied ())
                                  return ii;
                        return ALL_OCCUPIED;
                   private synchronized void updateServers (ActiveServers activeServers)
                        for (int ii = 0; ii < servers.length; ii++)
                             boolean wasActive = servers[ii].isActive ();
                             boolean nowActive = activeServers.isAlive (servers[ii].getHostName ());
                             if (wasActive && !nowActive)
                                  throttle.removeResource ();
                                  Logging.debugInfoLog ("Resource removed");
                             else if (!wasActive && nowActive)
                                  throttle.addResource ();
                                  Logging.debugInfoLog ("Resource added");
                             servers [ii].setActive (nowActive);
                   // MessageListener interface
                   //public void processMessage (Message msgIn)
                   public void onMessage (Message msgIn)
                        Logging.debugInfoLog ("Starting onMessage");
                        ActiveServers activeServers = null;
                        try
                             activeServers = new ActiveServers();
                        catch (Exception ignored) {}
                        Logging.debugInfoLog ("Active Servers file read");
                        updateServers (activeServers);
                        Logging.debugInfoLog ("Servers updated");
                        throttle.getResource ();
                        Logging.debugInfoLog ("Resource got");
                        try
              Logging.debugInfoLog ("0");
                        String msgTextIn;
                             ObjectMessage msgOut;
                             RateQuoteGetBase rateQuoteGet;
                             RateQuoteGetXML rateQuoteGetXML;
              Logging.debugInfoLog ("1");
                             if (msgIn == null)
              Logging.debugInfoLog ("2");
                                  rateQuoteGet = new RateQuoteGetBase ("Cannot receive a rate quote back from JMS.");
                                  msgTextIn = "";
                             else
              Logging.debugInfoLog ("3");
                                  if (msgIn instanceof TextMessage)
                                  msgTextIn = ((TextMessage)msgIn).getText();
                                  else
                                  msgTextIn = msgIn.toString();
              Logging.debugInfoLog ("4");
                                  bqueue = (Queue) msgIn.getJMSReplyTo ();
              Logging.debugInfoLog ("8");
                                  bsender = bsession.createSender(bqueue);
              Logging.debugInfoLog ("9");
                                  bsender.setDeliveryMode (javax.jms.DeliveryMode.NON_PERSISTENT);
              Logging.debugInfoLog ("10");
                                  Logging.debugInfoLog ("Prepareing to find unoccupied server");
                                  int selectedServer = findUnoccupiedServer ();
                                  Logging.debugInfoLog ("Unoccupied server found: " + selectedServer);
                                  if (selectedServer == ALL_OCCUPIED)
                                       rateQuoteGet = new RateQuoteGetBase ("No nonoccupied rating engines found.");
                                       msgTextIn = "";
                                  else
                                       servers [selectedServer].setOccupied ();
                                       Logging.debugInfoLog ("Set occupied: " + selectedServer);
                                       String hostname = servers [selectedServer].getHostName ();
                                       int portId = servers [selectedServer].getPortId ();
                                       rateQuoteGet = new RateQuoteGetBase (hostname, portId);
                                       rateQuoteGetXML = new RateQuoteGetXML (new RateQuoteGet (rateQuoteGet));
                                       rateQuoteGetXML.prepareXML ();
                                       servers [selectedServer].setUnOccupied ();
                                       Logging.debugInfoLog ("Set unoccupied: " + selectedServer);
                                       if (!rateQuoteGetXML.hasErrorOccured ())
                                            rateQuoteGet.sendXML (msgTextIn);
                                            rateQuoteGet.prepareXML ();
                             Logging.debugInfoLog("Message Received: " + msgTextIn );
                             msgOut = bsession.createObjectMessage ();
                             msgOut.setObject (rateQuoteGet);
                             bsender.send (msgOut, javax.jms.DeliveryMode.NON_PERSISTENT,
                                            javax.jms.Message.DEFAULT_PRIORITY, 18000000L);
                        Logging.debugInfoLog("Message Sent Back: " + rateQuoteGet.getXML());
                             Logging.debugInfoLog ("End of massage sent back");
                             rateQuoteGet.debugPrint ();
                        catch (JMSException jmse)
              Logging.debugInfoLog ("5");
                        jmse.printStackTrace();
              Logging.debugInfoLog ("6");
                        try
                             if (bsender != null)
                                  bsender.close ();
                        catch (JMSException ignored) {}
                        finally
                             bsender = null;
              Logging.debugInfoLog ("7");
                        try
                             throttle.freeResource ();
                             Logging.debugInfoLog ("Resource freed");
                             Logging.debugInfoLog ("Finishing onMessage");
                        catch (Exception ignored) {}
              * Create all the necessary objects for receiving
              * messages from a JMS queue.
                   public void init(Context ctx, String queueName, int countListeners) throws NamingException,
              JMSException
                        //Logging.debugInfoLog ("Class name: " + this.getClass().getName());
                        qconFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY);
                        qcon = qconFactory.createQueueConnection();
                        qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
                        bsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
                        try
                        queue = (Queue) ctx.lookup(queueName);
                        catch (NamingException ne)
                             ne.printStackTrace ();
                             //queue = (Queue) ctx.lookup (queueName);
                        //queue = qsession.createQueue (queueName);
                             //queue = JMSHelper.createPermanentQueueAsync(ctx, "closs", "ClossJMSServer",
              queueName, JNDI_FACTORY);
                             //JMSHelper.createPermanentQueueAsync(ctx, "ClossJMSServer", queueName, JNDI_FACTORY);
                             //queue = qsession.createQueue("ClossJMSServer/" + queueName);
                             //queue = createPermanentQueueAsync(ctx, jmsServerName, queueName, jndiName);
                        //ctx.bind(queueName, queue);
                        //qreceiver = qsession.createReceiver (queue);
                        //qreceiver.setMessageListener (this);
                        qcon.start();
                        sessionPoolFactory = (ServerSessionPoolFactory) ctx.lookup (SESSION_POOL_FACTORY);
                        sessionPool = sessionPoolFactory.getServerSessionPool (     qcon,
                                                                          countListeners,
                                                                          false,
                                                      Session.AUTO_ACKNOWLEDGE,
                                                      this.getClass().getName());
                        ConnectionConsumer consumer = qcon.createConnectionConsumer (queue, "", sessionPool,
              3*countListeners);
              * Close JMS objects.
                   public void close()
                        try
                             //if (qreceiver != null)
                             //     qreceiver.close();
                             if (consumer != null)
                                  consumer.close();
                        catch (JMSException ignored){}
                        //qreceiver = null;
                        consumer = null;
                        try
                             if (qsession != null)
                                  qsession.close();
                        catch (JMSException ignored){}
                        qsession = null;
                        try
                             if (bsender != null)
                                  bsender.close();
                        catch (JMSException ignored){}
                        bsender = null;
                        try
                             if (bsession != null)
                                  bsession.close();
                        catch (JMSException ignored){}
                        bsession = null;
                        try
                             if (qcon != null)
                                  qcon.close();
                        catch (JMSException ignored){}
                        qcon = null;
              * Receive a JMS message.
                   //public Message receive() throws JMSException
                   //     return qreceiver.receive ();
                   public static void main (String[] args) throws Exception
                        Message msg;
                        int len = args.length;
                        if (len %2 != 0 || len == 0)
                        Logging.debugInfoLog("Usage: java RateQuoteJMSResponse hostname portid hostname
              portid ...");
                        return;
                        int reCount = len/2;
                        throttle = new REServersThrottle (0);
                        servers = new REServer [reCount];
                        for (int ii = 0; ii < reCount; ii++)
                             servers [ii] = new REServer (args [2*ii], args [2*ii + 1]);
                        //Logging.debugInfoLog ("Arguments: " + args[0] + " " + args[1]);
                        InitialContext ic = getInitialContext (ClickProperties.getInitialContext());
                        RateQuoteJMSResponse qr = new RateQuoteJMSResponse ();
                        qr.init (ic, ClickProperties.getJMSQueue(), reCount);
                        Logging.debugInfoLog("JMS Rating Engine Responser Is Ready To Receive Messages.");
                        // Wait until a "quit" message has been received.
                        //synchronized (qr)
                   //     while (true)
                        //          msg = qr.receive ();
                        //          Logging.debugInfoLog ("Message received");
                        //          qr.processMessage (msg);
                        //qr.close();
                   private static InitialContext getInitialContext (String url) throws NamingException
                        Hashtable env = new Hashtable();
                        env.put (Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
                        env.put (Context.PROVIDER_URL, url);
                        return new InitialContext(env);
              And here is the output from weblogic console:
              <May 15, 2002 11:11:57 AM EDT> <Debug> <Debug Info Log> <Active Servers file rea
              d>
              <May 15, 2002 11:11:57 AM EDT> <Debug> <Debug Info Log> <Throttle max increased
              to: 1>
              <May 15, 2002 11:11:57 AM EDT> <Debug> <Debug Info Log> <Resource added>
              <May 15, 2002 11:11:57 AM EDT> <Debug> <Debug Info Log> <Servers updated>
              <May 15, 2002 11:11:57 AM EDT> <Debug> <Debug Info Log> <Throttle count increase
              d to: 1>
              <May 15, 2002 11:11:57 AM EDT> <Debug> <Debug Info Log> <Resource got>
              <May 15, 2002 11:11:57 AM EDT> <Debug> <Debug Info Log> <0>
              <May 15, 2002 11:11:57 AM EDT> <Debug> <Debug Info Log> <1>
              <May 15, 2002 11:11:57 AM EDT> <Debug> <Debug Info Log> <3>
              <May 15, 2002 11:11:57 AM EDT> <Debug> <Debug Info Log> <4>
              <May 15, 2002 11:11:57 AM EDT> <Debug> <Debug Info Log> <8>
              java.lang.RuntimeException: Client possibly malfunctioning as RuntimeException t
              hrown from the onMessage routine of the client
              at weblogic.jms.client.JMSSession.onMessage(JMSSession.java:1938)
              at weblogic.jms.client.JMSSession.run(JMSSession.java:881)
              at weblogic.jms.backend.BEServerSession.execute(BEServerSession.java:83)
              at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:137)
              at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:120)
              [config.xml]
              

              Thanks. It creates a new class each time onMessage () is called. I thought it uses
              an existing instance of the class.
              "Zach" <[email protected]> wrote:
              >You need to trap the exception inside the onMessage so you can see the
              >exception that is being thrown by the bsession.createSender call. This
              >stack trace doesn't give enough information. It is just a message saying
              >your code failed to handle and leaked an exception out of the onMessage.
              >If that is the line that failed, then try catch around it and look at the
              >stack trace for that exception.
              >
              >_sjz.
              >
              >"Alexander Rabinowitz" <[email protected]> wrote in message
              >news:[email protected]...
              >>
              >> I am using weblogic server 6.0 service pack 2.
              >> The problem is in runtime exception in JMS.
              >> Here is an exception I am getting:
              >> java.lang.RuntimeException: Client possibly malfunctioning as
              >RuntimeException thrown
              >> from the onMessage routine of the client
              >> at weblogic.jms.client.JMSSession.onMessage(JMSSession.java:1938)
              >> at weblogic.jms.client.JMSSession.run(JMSSession.java:881)
              >> at
              >weblogic.jms.backend.BEServerSession.execute(BEServerSession.java:83)
              >> at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:137)
              >> at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:120)
              >>
              >> This occurs in the line
              >>
              >> >bsender = bsession.createSender(bqueue);
              >>
              >> of the class, in the onMessage method.
              >>
              >> What is the reason for the exception? What can be done to fix it? I just
              >need to
              >> process several messages in parallel.
              >
              >
              >
              

  • Cache Synchronization Exception Handling

    I am setting up cache synchronization on WebLogic using JMS. I am looking into writing an exception handler to handle cache synchronization exceptions. The following statement in the documentation caught my attention:
    “As mentioned above, the TopLink cache does not begin the merge or update process until the database transaction has already been committed. This is quite beneficial in that it avoids letting uncommitted data into the shared cache, but should be recognized where transactional synchronization is considered. In cases where a merge may have failed there is no way to roll back the changes made to the database (although it is questionable whether this would be a good idea in any case). As a consequence, failures during remote merging can leave the cache in an inconsistent state. This makes it important to handle any errors that occur by performing cache normalization actions, such as resetting the cache, or even the server.”
    Suppose we have two app server instances, A and B. Instance A commits a change and sends the update notification to instance B. The merge fails on instance B with an optimistic lock exception.
    - I assume that a CacheSynchronizationException will be thrown. Will it be thrown on instance A, B, or both?
    - At this point which cache is inconsistent; A, B, or both?
    - The documentation suggests resetting the cache, but this seems a rather severe way of dealing with the problem. Is it feasible / effective to just refresh the objects in the change set of the CacheSynchronizationException?
    This is a simple exception handler. On receiving a CacheSynchronizationException it resets the cache and re-throws the exception.
    class ToplinkExceptionHandler implements ExceptionHandler{
         public Object handleException(RuntimeException exception) throws DatabaseException{
              if(exception instanceof CacheSynchronizationException){){
                   myServerSession.initializeAllIdentityMaps();
                   throw exception;
              }else{
                   throw exception;
    - Is this approach effective?
    - Once the cache is reset should the exception be re-thrown or should I consider it handled and swallow it? If I do swallow it what should the method return?
    Any advice would be appreciated.

    I had to fix a few errors (in our code) before getting it working. Since I have multiple sessions, I had to specify different multicast ports (actually I used a different multicast address itself) for each of the sessions. I was not setting the announcement delay on one of the sesssions and that was why it was announcing immediately upon coming up. Also I had to explicitly set asynchronous to false because it is true by default.
    BTW, we are not using CMP (entity beans) rather Java Objects. Our deployment has two Apache/Tomcat machines and two WebLogic machines. The WebLogic servers are in a round-robin cluster. The cache synchronization seems to be working fine for this configuration.
    Thanks.
    Anand R

  • Default Exception Handling in B2B

    Hi All,
    Need your help and advise on the below requirement we have currently:
    Source system sends an XML input to MW and therein, we transform it into PO_850 XSD and sends it to B2B. We are validating the XSD in B2B and then generating an EDI_PO_850 file and sending it to the Trading Partner. We are going to have 5 different Target Trading Partner. I have 2 questions w.r.t the default exception handling in place for Oracle B2B:
    1. Which Queue will have the Error Information for the above case? B2B_IN_Queue/B2B_OUT_Queue/B2B_IP_IN_Queue
    2. We would like to consume the error messages specific to a trading partner from the JMS Queue directly, how can we achieve it?
    Appreciate your help in this regard.
    Thanks in Advance
    Priyanka

    Hi Priyanka
    B2B operates in two modes for default internal queue communication - AQ and JMS. This is controlled in the Admin/Configuration page "use JMS queues" checkbox.
    In AQ, the queue to which the exception message is delivered would be IP_IN_QUEUE
    In JMS the queue to which the exception message is delivered would be B2B_IN_QUEUE. Since you speak about reading error message from the JMS queue directly, am thinking this would be the one of interest to you.
    In addition to the above we can create custom JMS internal delivery queue and this can be associated to the Exception Queue which can be assigned in the Admin/Configuration page.
    With regards to reading the exception msg specific to the trading partner from the JMS Queue directly, this can be done by adding a check on the dequeue process. Each exception message is populated with From_Party and To_Party information. In the outbound delivery case, the exception message should have To_Party set as the partner's name. This can be checked.
    Hope that helps.
    Regards
    Arun

  • EDN Mediator exception handling

    Hi All,
    I am subscrbing to business events through mediator.and then i am using the database adaptor to insert the data into a table.
    I want to implement exception handling for the events.The delivery policies for event in mediator is guaranteed.Howver i still see the oracle text as The event is guaranteed to be handed to the subscriber, but because there is no global transaction, there is a possibility that a system failure can cause an event to be delivered more than once. If the subscriber throws an exception (or fails in any way), the exception is logged, but the event is not resent.
    Does the above statement menas that i will lose my business event data.I cannot afford to miss any business events in any case.So i would like to know if in guaranteed delivery of events if the subscriber gives an error , i want my events to be still stored in database and not give excpetion to the publisher.
    Pls help its urgent
    Regards.....

    I think it is clearly defined here -
    http://docs.oracle.com/cd/E28280_01/dev.1111/e10224/obe_intro.htm#CHDIBHBE
    guaranteed
    Events are delivered to the subscriber asynchronously without a global transaction. The subscriber can choose to create its own local transaction for processing, but it is committed independently of the rest of event processing. This option incurs a lower cost than the one and only one option because there is only the trip to one queue (the main event queue). In addition, EDN does not attempt to resend an event (regardless of the backing store being AQ or JMS). If one or more subscribers fail to consume the event (while others succeed), those subscribers lose the message. In this respect, guaranteed delivery actually means best effort delivery; that is, it is not guaranteed that each subscriber definitely consumes the message.
    So "Guranteed" is just a bad choice of word. It actually means "Best-Effort" so if you cannot afford to miss a single message then avoid using EDN in your solution.
    Regards,
    Anuj

  • MC.9 and MCY1 and Exception Handling in (Logistics Inf. Sys)LIS

    Hi,
    I want the 'Valuated Stock Value" greater then or equal to zero (>=) appear in the MC.9 report. I can create 'Exception' in MCY1 but am unable to do so. Once I am in MCY1; I choose 'Requirements' then Key Figure 'Valuated Stock Value' then  'Type of condition' is 'Threshold Val. Anal.' is set to '> 0'. However, the report still displays zero values in MC.9. I don't want to display 'Valuated Stock Value' zero to be displayed on the report. Please help.
    Thanks
    Naved

    Hey Chris,
    I got the point for exception handling in weblogic 9.2. We ae using 9.2. It comes up with the concept of shared page flows which means all my unhandled exceptions are thrown to the shared page flow controller. There based on the type of exception, i can forward the request to appropraite page.
    Thanks anywyas,
    Saurabh

  • PL/SQL 101 : Exception Handling

    Frequently I see questions and issues around the use of Exception/Error Handling in PL/SQL.  More often than not the issue comes from the questioners misunderstanding about how PL/SQL is constructed and executed, so I thought I'd write a small article covering the key concepts to give a clear picture of how it all hangs together. (Note: the examples are just showing examples of the exception handling structure, and should not be taken as truly valid code for ways of handling things)
    Exception Handling
    Contents
    1. Understanding Execution Blocks (part 1)
    2. Execution of the Execution Block
    3. Exceptions
    4. Understanding Execution Blocks (part 2)
    5. How to continue exection of statements after an exception
    6. User defined exceptions
    7. Line number of exception
    8. Exceptions within code within the exception block
    1. Understanding Execution Blocks (part 1)
    The first thing that one needs to understand is almost taking us back to the basics of PL/SQL... how a PL/SQL execution block is constructed.
    Essentially an execution block is made of 3 sections...
    +---------------------------+
    |    Declaration Section    |
    +---------------------------+
    |    Statements  Section    |
    +---------------------------+
    |     Exception Section     |
    +---------------------------+
    The Declaration section is the part defined between the PROCEDURE/FUNCTION header or the DECLARE keyword (for anonymous blocks) and the BEGIN keyword.  (Optional section)
    The Statements section is where your code goes and lies between the BEGIN keyword and the EXCEPTION keyword (or END keyword if there is no EXCEPTION section).  (Mandatory section)
    The Exception section is where any exception handling goes and lies between the EXCEPTION keyword at the END keyword. (Optional section)
    Example of an anonymous block...
    DECLARE
      .. declarative statements go here ..
    BEGIN
      .. code statements go here ..
    EXCEPTION
      .. exception handlers go here ..
    END;
    Example of a procedure/function block...
    [CREATE OR REPLACE] (PROCEDURE|FUNCTION) <proc or fn name> [(<parameters>)] [RETURN <datatype>] (IS|AS)
      .. declarative statements go here ..
    BEGIN
      .. code statements go here ..
    EXCEPTION
      .. exception handlers go here ..
    END;
    (Note: The same can also be done for packages, but let's keep it simple)
    2. Execution of the Execution Block
    This may seem a simple concept, but it's surprising how many people have issues showing they haven't grasped it.  When an Execution block is entered, the declaration section is processed, creating a scope of variables, types , cursors, etc. to be visible to the execution block and then execution enters into the Statements section.  Each statment in the statements section is executed in turn and when the execution completes the last statment the execution block is exited back to whatever called it.
    3. Exceptions
    Exceptions generally happen during the execution of statements in the Statements section.  When an exception happens the execution of statements jumps immediately into the exception section.  In this section we can specify what exceptions we wish to 'capture' or 'trap' and do one of the two following things...
    (Note: The exception section still has access to all the declared items in the declaration section)
    3.i) Handle the exception
    We do this when we recognise what the exception is (most likely it's something we expect to happen) and we have a means of dealing with it so that our application can continue on.
    Example...
    (without the exception handler the exception is passed back to the calling code, in this case SQL*Plus)
    SQL> ed
    Wrote file afiedt.buf
      1  declare
      2    v_name VARCHAR2(20);
      3  begin
      4    select ename
      5    into   v_name
      6    from   emp
      7    where  empno = &empno;
      8    dbms_output.put_line(v_name);
      9* end;
    SQL> /
    Enter value for empno: 123
    old   7:   where  empno = &empno;
    new   7:   where  empno = 123;
    declare
    ERROR at line 1:
    ORA-01403: no data found
    ORA-06512: at line 4
    (with an exception handler, we capture the exception, handle it how we want to, and the calling code is happy that there is no error for it to report)
    SQL> ed
    Wrote file afiedt.buf
      1  declare
      2    v_name VARCHAR2(20);
      3  begin
      4    select ename
      5    into   v_name
      6    from   emp
      7    where  empno = &empno;
      8    dbms_output.put_line(v_name);
      9  exception
    10    when no_data_found then
    11      dbms_output.put_line('There is no employee with this employee number.');
    12* end;
    SQL> /
    Enter value for empno: 123
    old   7:   where  empno = &empno;
    new   7:   where  empno = 123;
    There is no employee with this employee number.
    PL/SQL procedure successfully completed.
    3.ii) Raise the exception
    We do this when:-
    a) we recognise the exception, handle it but still want to let the calling code know that it happened
    b) we recognise the exception, wish to log it happened and then let the calling code deal with it
    c) we don't recognise the exception and we want the calling code to deal with it
    Example of b)
    SQL> ed
    Wrote file afiedt.buf
      1  declare
      2    v_name VARCHAR2(20);
      3    v_empno NUMBER := &empno;
      4  begin
      5    select ename
      6    into   v_name
      7    from   emp
      8    where  empno = v_empno;
      9    dbms_output.put_line(v_name);
    10  EXCEPTION
    11    WHEN no_data_found THEN
    12      INSERT INTO sql_errors (txt)
    13      VALUES ('Search for '||v_empno||' failed.');
    14      COMMIT;
    15      RAISE;
    16* end;
    SQL> /
    Enter value for empno: 123
    old   3:   v_empno NUMBER := &empno;
    new   3:   v_empno NUMBER := 123;
    declare
    ERROR at line 1:
    ORA-01403: no data found
    ORA-06512: at line 15
    SQL> select * from sql_errors;
    TXT
    Search for 123 failed.
    SQL>
    Example of c)
    SQL> ed
    Wrote file afiedt.buf
      1  declare
      2    v_name VARCHAR2(20);
      3    v_empno NUMBER := &empno;
      4  begin
      5    select ename
      6    into   v_name
      7    from   emp
      8    where  empno = v_empno;
      9    dbms_output.put_line(v_name);
    10  EXCEPTION
    11    WHEN no_data_found THEN
    12      INSERT INTO sql_errors (txt)
    13      VALUES ('Search for '||v_empno||' failed.');
    14      COMMIT;
    15      RAISE;
    16    WHEN others THEN
    17      RAISE;
    18* end;
    SQL> /
    Enter value for empno: 'ABC'
    old   3:   v_empno NUMBER := &empno;
    new   3:   v_empno NUMBER := 'ABC';
    declare
    ERROR at line 1:
    ORA-06502: PL/SQL: numeric or value error: character to number conversion error
    ORA-06512: at line 3
    SQL> select * from sql_errors;
    TXT
    Search for 123 failed.
    SQL>
    As you can see from the sql_errors log table, no log was written so the WHEN others exception was the exception that raised the error to the calling code (SQL*Plus)
    4. Understanding Execution Blocks (part 2)
    Ok, so now we understand the very basics of an execution block and what happens when an exception happens.  Let's take it a step further...
    Execution blocks are not just a single simple block in most cases.  Often, during our statements section we have a need to call some reusable code and we do that by calling a procedure or function.  Effectively this nests the procedure or function's code as another execution block within the current statement section so, in terms of execution, we end up with something like...
    +---------------------------------+
    |    Declaration Section          |
    +---------------------------------+
    |    Statements  Section          |
    |            .                    |
    |  +---------------------------+  |
    |  |    Declaration Section    |  |
    |  +---------------------------+  |
    |  |    Statements  Section    |  |
    |  +---------------------------+  |
    |  |     Exception Section     |  |
    |  +---------------------------+  |
    |            .                    |
    +---------------------------------+
    |     Exception Section           |
    +---------------------------------+
    Example... (Note: log_trace just writes some text to a table for tracing)
    SQL> create or replace procedure a as
      2    v_dummy NUMBER := log_trace('Procedure A''s Declaration Section');
      3  begin
      4    v_dummy := log_trace('Procedure A''s Statement Section');
      5    v_dummy := 1/0; -- cause an exception
      6  exception
      7    when others then
      8      v_dummy := log_trace('Procedure A''s Exception Section');
      9      raise;
    10  end;
    11  /
    Procedure created.
    SQL> create or replace procedure b as
      2    v_dummy NUMBER := log_trace('Procedure B''s Declaration Section');
      3  begin
      4    v_dummy := log_trace('Procedure B''s Statement Section');
      5    a; -- HERE the execution passes to the declare/statement/exception sections of A
      6  exception
      7    when others then
      8      v_dummy := log_trace('Procedure B''s Exception Section');
      9      raise;
    10  end;
    11  /
    Procedure created.
    SQL> exec b;
    BEGIN b; END;
    ERROR at line 1:
    ORA-01476: divisor is equal to zero
    ORA-06512: at "SCOTT.B", line 9
    ORA-06512: at line 1
    SQL> select * from code_trace;
    TXT
    Procedure B's Declaration Section
    Procedure B's Statement Section
    Procedure A's Declaration Section
    Procedure A's Statement Section
    Procedure A's Exception Section
    Procedure B's Exception Section
    6 rows selected.
    SQL>
    Likewise, execution blocks can be nested deeper and deeper.
    5. How to continue exection of statements after an exception
    One of the common questions asked is how to return execution to the statement after the one that created the exception and continue on.
    Well, firstly, you can only do this for statements you expect to raise an exception, such as when you want to check if there is no data found in a query.
    If you consider what's been shown above you could put any statement you expect to cause an exception inside it's own procedure or function with it's own exception section to handle the exception without raising it back to the calling code.  However, the nature of procedures and functions is really to provide a means of re-using code, so if it's a statement you only use once it seems a little silly to go creating individual procedures for these.
    Instead, you nest execution blocks directly, to give the same result as shown in the diagram at the start of part 4 of this article.
    SQL> ed
    Wrote file afiedt.buf
      1  create or replace procedure b (p_empno IN VARCHAR2) as
      2    v_dummy NUMBER := log_trace('Procedure B''s Declaration Section');
      3  begin
      4    v_dummy := log_trace('Procedure B''s Statement Section');
      5    -- Here we start another execution block nested in the first one...
      6    declare
      7      v_dummy NUMBER := log_trace('Nested Block Declaration Section');
      8    begin
      9      v_dummy := log_trace('Nested Block Statement Section');
    10      select empno
    11        into   v_dummy
    12        from   emp
    13       where  empno = p_empno; -- Note: the parameters and variables from
                                         parent execution block are available to use!
    14    exception
    15      when no_data_found then
    16        -- This is an exception we can handle so we don't raise it
    17        v_dummy := log_trace('No employee was found');
    18        v_dummy := log_trace('Nested Block Exception Section - Exception Handled');
    19      when others then
    20        -- Other exceptions we can't handle so we raise them
    21        v_dummy := log_trace('Nested Block Exception Section - Exception Raised');
    22        raise;
    23    end;
    24    -- ...Here endeth the nested execution block
    25    -- As the nested block handled it's exception we come back to here...
    26    v_dummy := log_trace('Procedure B''s Statement Section Continued');
    27  exception
    28    when others then
    29      -- We'll only get to here if an unhandled exception was raised
    30      -- either in the nested block or in procedure b's statement section
    31      v_dummy := log_trace('Procedure B''s Exception Section');
    32      raise;
    33* end;
    SQL> /
    Procedure created.
    SQL> exec b(123);
    PL/SQL procedure successfully completed.
    SQL> select * from code_trace;
    TXT
    Procedure B's Declaration Section
    Procedure B's Statement Section
    Nested Block Declaration Section
    Nested Block Statement Section
    No employee was found
    Nested Block Exception Section - Exception Handled
    Procedure B's Statement Section Continued
    7 rows selected.
    SQL> truncate table code_trace;
    Table truncated.
    SQL> exec b('ABC');
    BEGIN b('ABC'); END;
    ERROR at line 1:
    ORA-01722: invalid number
    ORA-06512: at "SCOTT.B", line 32
    ORA-06512: at line 1
    SQL> select * from code_trace;
    TXT
    Procedure B's Declaration Section
    Procedure B's Statement Section
    Nested Block Declaration Section
    Nested Block Statement Section
    Nested Block Exception Section - Exception Raised
    Procedure B's Exception Section
    6 rows selected.
    SQL>
    You can see from this that, very simply, the code that we expected may have an exception was able to either handle the exception and return to the outer execution block to continue execution, or if an unexpected exception occurred then it was able to be raised up to the outer exception section.
    6. User defined exceptions
    There are three sorts of 'User Defined' exceptions.  There are logical situations (e.g. business logic) where, for example, certain criteria are not met to complete a task, and there are existing Oracle errors that you wish to give a name to in order to capture them in the exception section.  The third is raising your own exception messages with our own exception numbers.  Let's look at the first one...
    Let's say I have tables which detail stock availablility and reorder levels...
    SQL> select * from reorder_level;
       ITEM_ID STOCK_LEVEL
             1          20
             2          20
             3          10
             4           2
             5           2
    SQL> select * from stock;
       ITEM_ID ITEM_DESC  STOCK_LEVEL
             1 Pencils             10
             2 Pens                 2
             3 Notepads            25
             4 Stapler              5
             5 Hole Punch           3
    SQL>
    Now, our Business has told the administrative clerk to check stock levels and re-order anything that is below the re-order level, but not to hold stock of more than 4 times the re-order level for any particular item.  As an IT department we've been asked to put together an application that will automatically produce the re-order documents upon the clerks request and, because our company is so tight-ar*ed about money, they don't want to waste any paper with incorrect printouts so we have to ensure the clerk can't order things they shouldn't.
    SQL> ed
    Wrote file afiedt.buf
      1  create or replace procedure re_order(p_item_id NUMBER, p_quantity NUMBER) is
      2    cursor cur_stock_reorder is
      3      select s.stock_level
      4            ,r.stock_level as reorder_level
      5            ,(r.stock_level*4) as reorder_limit
      6      from stock s join reorder_level r on (s.item_id = r.item_id)
      7      where s.item_id = p_item_id;
      8    --
      9    v_stock cur_stock_reorder%ROWTYPE;
    10  begin
    11    OPEN cur_stock_reorder;
    12    FETCH cur_stock_reorder INTO v_stock;
    13    IF cur_stock_reorder%NOTFOUND THEN
    14      RAISE no_data_found;
    15    END IF;
    16    CLOSE cur_stock_reorder;
    17    --
    18    IF v_stock.stock_level >= v_stock.reorder_level THEN
    19      -- Stock is not low enough to warrant an order
    20      DBMS_OUTPUT.PUT_LINE('Stock has not reached re-order level yet!');
    21    ELSE
    22      IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
    23        -- Required amount is over-ordering
    24        DBMS_OUTPUT.PUT_LINE('Quantity specified is too much.  Max for this item: '
                                     ||to_char(v_stock.reorder_limit-v_stock.stock_level));
    25      ELSE
    26        DBMS_OUTPUT.PUT_LINE('Order OK.  Printing Order...');
    27        -- Here goes our code to print the order
    28      END IF;
    29    END IF;
    30    --
    31  exception
    32    WHEN no_data_found THEN
    33      CLOSE cur_stock_reorder;
    34      DBMS_OUTPUT.PUT_LINE('Invalid Item ID.');
    35* end;
    SQL> /
    Procedure created.
    SQL> exec re_order(10,100);
    Invalid Item ID.
    PL/SQL procedure successfully completed.
    SQL> exec re_order(3,40);
    Stock has not reached re-order level yet!
    PL/SQL procedure successfully completed.
    SQL> exec re_order(1,100);
    Quantity specified is too much.  Max for this item: 70
    PL/SQL procedure successfully completed.
    SQL> exec re_order(2,50);
    Order OK.  Printing Order...
    PL/SQL procedure successfully completed.
    SQL>
    Ok, so that code works, but it's a bit messy with all those nested IF statements. Is there a cleaner way perhaps?  Wouldn't it be nice if we could set up our own exceptions...
    SQL> ed
    Wrote file afiedt.buf
      1  create or replace procedure re_order(p_item_id NUMBER, p_quantity NUMBER) is
      2    cursor cur_stock_reorder is
      3      select s.stock_level
      4            ,r.stock_level as reorder_level
      5            ,(r.stock_level*4) as reorder_limit
      6      from stock s join reorder_level r on (s.item_id = r.item_id)
      7      where s.item_id = p_item_id;
      8    --
      9    v_stock cur_stock_reorder%ROWTYPE;
    10    --
    11    -- Let's declare our own exceptions for business logic...
    12    exc_not_warranted EXCEPTION;
    13    exc_too_much      EXCEPTION;
    14  begin
    15    OPEN cur_stock_reorder;
    16    FETCH cur_stock_reorder INTO v_stock;
    17    IF cur_stock_reorder%NOTFOUND THEN
    18      RAISE no_data_found;
    19    END IF;
    20    CLOSE cur_stock_reorder;
    21    --
    22    IF v_stock.stock_level >= v_stock.reorder_level THEN
    23      -- Stock is not low enough to warrant an order
    24      RAISE exc_not_warranted;
    25    END IF;
    26    --
    27    IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
    28      -- Required amount is over-ordering
    29      RAISE exc_too_much;
    30    END IF;
    31    --
    32    DBMS_OUTPUT.PUT_LINE('Order OK.  Printing Order...');
    33    -- Here goes our code to print the order
    34    --
    35  exception
    36    WHEN no_data_found THEN
    37      CLOSE cur_stock_reorder;
    38      DBMS_OUTPUT.PUT_LINE('Invalid Item ID.');
    39    WHEN exc_not_warranted THEN
    40      DBMS_OUTPUT.PUT_LINE('Stock has not reached re-order level yet!');
    41    WHEN exc_too_much THEN
    42      DBMS_OUTPUT.PUT_LINE('Quantity specified is too much.  Max for this item: '
                                  ||to_char(v_stock.reorder_limit-v_stock.stock_level));
    43* end;
    SQL> /
    Procedure created.
    SQL> exec re_order(10,100);
    Invalid Item ID.
    PL/SQL procedure successfully completed.
    SQL> exec re_order(3,40);
    Stock has not reached re-order level yet!
    PL/SQL procedure successfully completed.
    SQL> exec re_order(1,100);
    Quantity specified is too much.  Max for this item: 70
    PL/SQL procedure successfully completed.
    SQL> exec re_order(2,50);
    Order OK.  Printing Order...
    PL/SQL procedure successfully completed.
    SQL>
    That's better.  And now we don't have to use all those nested IF statements and worry about it accidently getting to code that will print the order out as, once one of our user defined exceptions is raised, execution goes from the Statements section into the Exception section and all handling of errors is done in one place.
    Now for the second sort of user defined exception...
    A new requirement has come in from the Finance department who want to have details shown on the order that show a re-order 'indicator' based on the formula ((maximum allowed stock - current stock)/re-order quantity), so this needs calculating and passing to the report...
    SQL> ed
    Wrote file afiedt.buf
      1  create or replace procedure re_order(p_item_id NUMBER, p_quantity NUMBER) is
      2    cursor cur_stock_reorder is
      3      select s.stock_level
      4            ,r.stock_level as reorder_level
      5            ,(r.stock_level*4) as reorder_limit
      6            ,(((r.stock_level*4)-s.stock_level)/p_quantity) as finance_factor
      7      from stock s join reorder_level r on (s.item_id = r.item_id)
      8      where s.item_id = p_item_id;
      9    --
    10    v_stock cur_stock_reorder%ROWTYPE;
    11    --
    12    -- Let's declare our own exceptions for business logic...
    13    exc_not_warranted EXCEPTION;
    14    exc_too_much      EXCEPTION;
    15  begin
    16    OPEN cur_stock_reorder;
    17    FETCH cur_stock_reorder INTO v_stock;
    18    IF cur_stock_reorder%NOTFOUND THEN
    19      RAISE no_data_found;
    20    END IF;
    21    CLOSE cur_stock_reorder;
    22    --
    23    IF v_stock.stock_level >= v_stock.reorder_level THEN
    24      -- Stock is not low enough to warrant an order
    25      RAISE exc_not_warranted;
    26    END IF;
    27    --
    28    IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
    29      -- Required amount is over-ordering
    30      RAISE exc_too_much;
    31    END IF;
    32    --
    33    DBMS_OUTPUT.PUT_LINE('Order OK.  Printing Order...');
    34    -- Here goes our code to print the order, passing the finance_factor
    35    --
    36  exception
    37    WHEN no_data_found THEN
    38      CLOSE cur_stock_reorder;
    39      DBMS_OUTPUT.PUT_LINE('Invalid Item ID.');
    40    WHEN exc_not_warranted THEN
    41      DBMS_OUTPUT.PUT_LINE('Stock has not reached re-order level yet!');
    42    WHEN exc_too_much THEN
    43      DBMS_OUTPUT.PUT_LINE('Quantity specified is too much.  Max for this item: '
                                  ||to_char(v_stock.reorder_limit-v_stock.stock_level));
    44* end;
    SQL> /
    Procedure created.
    SQL> exec re_order(2,40);
    Order OK.  Printing Order...
    PL/SQL procedure successfully completed.
    SQL> exec re_order(2,0);
    BEGIN re_order(2,0); END;
    ERROR at line 1:
    ORA-01476: divisor is equal to zero
    ORA-06512: at "SCOTT.RE_ORDER", line 17
    ORA-06512: at line 1
    SQL>
    Hmm, there's a problem if the person specifies a re-order quantity of zero.  It raises an unhandled exception.
    Well, we could put a condition/check into our code to make sure the parameter is not zero, but again we would be wrapping our code in an IF statement and not dealing with the exception in the exception handler.
    We could do as we did before and just include a simple IF statement to check the value and raise our own user defined exception but, in this instance the error is standard Oracle error (ORA-01476) so we should be able to capture it inside the exception handler anyway... however...
    EXCEPTION
      WHEN ORA-01476 THEN
    ... is not valid.  What we need is to give this Oracle error a name.
    This is done by declaring a user defined exception as we did before and then associating that name with the error number using the PRAGMA EXCEPTION_INIT statement in the declaration section.
    SQL> ed
    Wrote file afiedt.buf
      1  create or replace procedure re_order(p_item_id NUMBER, p_quantity NUMBER) is
      2    cursor cur_stock_reorder is
      3      select s.stock_level
      4            ,r.stock_level as reorder_level
      5            ,(r.stock_level*4) as reorder_limit
      6            ,(((r.stock_level*4)-s.stock_level)/p_quantity) as finance_factor
      7      from stock s join reorder_level r on (s.item_id = r.item_id)
      8      where s.item_id = p_item_id;
      9    --
    10    v_stock cur_stock_reorder%ROWTYPE;
    11    --
    12    -- Let's declare our own exceptions for business logic...
    13    exc_not_warranted EXCEPTION;
    14    exc_too_much      EXCEPTION;
    15    --
    16    exc_zero_quantity EXCEPTION;
    17    PRAGMA EXCEPTION_INIT(exc_zero_quantity, -1476);
    18  begin
    19    OPEN cur_stock_reorder;
    20    FETCH cur_stock_reorder INTO v_stock;
    21    IF cur_stock_reorder%NOTFOUND THEN
    22      RAISE no_data_found;
    23    END IF;
    24    CLOSE cur_stock_reorder;
    25    --
    26    IF v_stock.stock_level >= v_stock.reorder_level THEN
    27      -- Stock is not low enough to warrant an order
    28      RAISE exc_not_warranted;
    29    END IF;
    30    --
    31    IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
    32      -- Required amount is over-ordering
    33      RAISE exc_too_much;
    34    END IF;
    35    --
    36    DBMS_OUTPUT.PUT_LINE('Order OK.  Printing Order...');
    37    -- Here goes our code to print the order, passing the finance_factor
    38    --
    39  exception
    40    WHEN exc_zero_quantity THEN
    41      DBMS_OUTPUT.PUT_LINE('Quantity of 0 (zero) is invalid.');
    42    WHEN no_data_found THEN
    43      CLOSE cur_stock_reorder;
    44      DBMS_OUTPUT.PUT_LINE('Invalid Item ID.');
    45    WHEN exc_not_warranted THEN
    46      DBMS_OUTPUT.PUT_LINE('Stock has not reached re-order level yet!');
    47    WHEN exc_too_much THEN
    48      DBMS_OUTPUT.PUT_LINE('Quantity specified is too much.  Max for this item: '
                                  ||to_char(v_stock.reorder_limit-v_stock.stock_level));
    49* end;
    SQL> /
    Procedure created.
    SQL> exec re_order(2,0);
    Quantity of 0 (zero) is invalid.
    PL/SQL procedure successfully completed.
    SQL>
    Lastly, let's look at raising our own exceptions with our own exception numbers...
    SQL> ed
    Wrote file afiedt.buf
      1  create or replace procedure re_order(p_item_id NUMBER, p_quantity NUMBER) is
      2    cursor cur_stock_reorder is
      3      select s.stock_level
      4            ,r.stock_level as reorder_level
      5            ,(r.stock_level*4) as reorder_limit
      6            ,(((r.stock_level*4)-s.stock_level)/p_quantity) as finance_factor
      7      from stock s join reorder_level r on (s.item_id = r.item_id)
      8      where s.item_id = p_item_id;
      9    --
    10    v_stock cur_stock_reorder%ROWTYPE;
    11    --
    12    exc_zero_quantity EXCEPTION;
    13    PRAGMA EXCEPTION_INIT(exc_zero_quantity, -1476);
    14  begin
    15    OPEN cur_stock_reorder;
    16    FETCH cur_stock_reorder INTO v_stock;
    17    IF cur_stock_reorder%NOTFOUND THEN
    18      RAISE no_data_found;
    19    END IF;
    20    CLOSE cur_stock_reorder;
    21    --
    22    IF v_stock.stock_level >= v_stock.reorder_level THEN
    23      -- Stock is not low enough to warrant an order
    24      [b]RAISE_APPLICATION_ERROR(-20000, 'Stock has not reached re-order level yet!');[/b]
    25    END IF;
    26    --
    27    IF v_stock.stock_level + p_quantity > v_stock.reorder_limit THEN
    28      -- Required amount is over-ordering
    29     

    its nice article, have put up this one the blog
    site,Nah, I don't have time to blog, but if one of the other Ace's/Experts wants to copy it to a blog with reference back to here (and all due credit given ;)) then that's fine by me.
    I'd go for a book like "Selected articles by OTN members" or something. Does anybody have a list of links of all those mentioned articles?Just these ones I've bookmarked...
    Introduction to regular expressions ... by CD
    When your query takes too long ... by Rob van Wijk
    How to pipeline a function with a dynamic number of columns? by ascheffer
    PL/SQL 101 : Exception Handling by BluShadow

  • Delete Statement Exception Handling

    Hi guys,
    I have a problem in my procedure. There are 3 parameters that I am passing into the procedure. I am matching these parameters to those in the table to delete one record at a time.
    For example if I would like to delete the record with the values ('900682',3,'29-JUL-2008') as parameters, it deletes the record from the table but then again when I execute it with the same parameters it should show me an error message but it again says 'Deleted the Transcript Request.....' Can you please help me with this?
    PROCEDURE p_delete_szptpsr_1 (p_shttran_id IN saturn.shttran.shttran_id%TYPE,
    p_shttran_seq_no IN saturn.shttran.shttran_seq_no%TYPE,
    p_shttran_request_date IN saturn.shttran.shttran_request_date%TYPE) IS
    BEGIN
    DELETE FROM saturn.shttran
    WHERE shttran.shttran_id = p_shttran_id
    and shttran.shttran_seq_no = p_shttran_seq_no
    and trunc(shttran_request_date) = trunc(p_shttran_request_date);
    DBMS_OUTPUT.PUT_LINE('Deleted the Transcript Request Seq No (' || p_shttran_seq_no || ') of the Student (' || p_shttran_id ||') for the requested date of (' || p_shttran_request_date ||')');
    COMMIT;
    EXCEPTION WHEN NO_DATA_FOUND THEN
    DBMS_OUTPUT.PUT_LINE('Error: The supplied Notre Dame Student ID = (' || p_shttran_id ||
    '), Transcript Request No = (' || p_shttran_seq_no || '), Request Date = (' || p_shttran_request_date || ') was not found.');
    END p_delete_szptpsr_1;
    Should I have a SELECT statement to use NO_DATA_FOUND ???

    A DELETE statement that deletes no rows (just like an UPDATE statement that updates no rows) is not an error to Oracle. Oracle won't throw any exception.
    If you want your code to throw an exception, you'll need to write that logic. You could throw a NO_DATA_FOUND exception yourself, i.e.
    IF( SQL%ROWCOUNT = 0 )
    THEN
      RAISE no_data_found;
    END IF;If you are just going to catch the exception, though, you could just embed whatever code you would use to handle the exception in your IF statement, i.e.
    IF( SQL%ROWCOUNT = 0 )
    THEN
      <<do something about the exception>>
    END IF;In your original code, your exception handler is just a DBMS_OUTPUT statement. That is incredibly dangerous in real production code. You are relying on the fact that the client has enabled output, that the client has allocated a large enough buffer, that the user is going to see the message, and that the procedure will never be called from any piece of code that would ever care if it succeeded or failed. There are vanishingly few situations where those are safe things to rely on.
    Justin

  • Exception handling is not working in GCC compile shared object

    Hello,
    I am facing very strange issue on Solaris x86_64 platform with C++ code compiled usging gcc.3.4.3.
    I have compiled shared object that load into web server process space while initialization. Whenever any exception generate in code base, it is not being caught by exception handler. Even though exception handlers are there. Same code is working fine since long time but on Solaris x86, Sparc arch, Linux platform
    With Dbx, I am getting following stack trace.
    Stack trace is
    dbx: internal error: reference through NULL pointer at line 973 in file symbol.cc
    [1] 0x11335(0x1, 0x1, 0x474e5543432b2b00, 0x59cb60, 0xfffffd7fffdff2b0, 0x11335), at 0x11335
    ---- hidden frames, use 'where -h' to see them all ----
    =>[4] __cxa_throw(obj = (nil), tinfo = (nil), dest = (nil), , line 75 in "eh_throw.cc"
    [5] OBWebGate_Authent(r = 0xfffffd7fff3fb300), line 86 in "apache.cpp"
    [6] ap_run_post_config(0x0, 0x0, 0x0, 0x0, 0x0, 0x0), at 0x444624
    [7] main(0x0, 0x0, 0x0, 0x0, 0x0, 0x0), at 0x42c39a
    I am using following link options.
    Compile option is
    /usr/sfw/bin/g++ -c -I/scratch/ashishas/view_storage/build/coreid1014/palantir/apache22/solaris-x86_64/include -m64 -fPIC -D_REENTRANT -Wall -g -o apache.o apache.cpp
    Link option is
    /usr/sfw/bin/g++ -shared -m64 -o apache.so apache.o -lsocket -lnsl -ldl -lpthread -lthread
    At line 86, we are just throwing simple exception which have catch handlers in place. Also we do have catch(...) handler as well.
    Surpursing things are..same issue didn't observe if we make it as executable.
    Issue only comes if this is shared object loaded on webserver. If this is plain shared object, opened by anyother exe, it works fine.
    Can someone help me out. This is completly blocking issue for us. Using Solaris Sun Studio compiler is no option as of now.

    shared object that load into web server process space
    ... same issue didn't observe if we make it as executable.When you "inject" your shared object into some other process a well-being of your exception handling depends on that other process.
    Mechanics of x64 stack traversing (unwind) performed when you throw the exception is quite complicated,
    particularly involving a "nearly-standartized" Unwind interface (say, Unwind_RaiseException).
    When we are talking about g++ on Solaris there are two implementations of unwind interface, one in libc and one in libgcc_s.so.
    When you g++-compile the executable you get it directly linked with libgcc_s.so and Unwind stuff resolves into libgccs.
    When g++-compiled shared object is loaded into non-g++-compiled executable's process _Unwind calls are most likely already resolved into Solaris libc.
    Thats why you might see the difference.
    Now, what exactly causes this difference can vary, I can only speculate.
    All that would not be a problem if _Unwind interface was completely standartized and properly implemented.
    However there are two issues currently:
    * gcc (libstdc++ in particular) happens to use additional non-standard _Unwind calls which are not present in Solaris libc
    naturally, implementation details of Unwind implementation in libc differs to that of libgccs, so when all the standard _Unwind
    routines are resolved into Solaris version and one non-standard _Unwind routine is resolved into gcc version you get a problem
    (most likely that is what happens with you)
    * libc Unwind sometimes is unable to decipher the code generated by gcc.
    However that is likely to happen with modern gcc (say, 4.4+) and not that likely with 3.4.3
    Btw, you can check your call frame to see where _Unwind calls come from:
    where -h -lIf you indeed stomped on "mixed _Unwind" problem then the only chance for you is to play with linker
    so it binds Unwind stuff from your library directly into libgccs.
    Not tried it myself though.
    regards,
    __Fedor.

  • Exception handling to catch the outcome of a select

    Hello,
    I want to use exception handling to exit me out of a function module.  I want to have one exception for all errors.
    For example, if this select statement does not work, how do I finish up this code to make it work.
    error type cx_bsx
    try
    select * from t001 where BUKRS = '!@#$'
    catch <not sure what> into INTO error
    raise exception error
    endtry.
    When I use cx_bsx with the catch, nothing happens even though the select statement fails. Basically I want the catch to work in the same manner as this:
    if sy-subrc ne 0.
    raise error_table_read.
    endif.

    If this code is in a function module, then why not just use the function  module exceptions.
    if sy-subrc ne 0.
    raise error_table_read.
    endif.
    What are you gaining by "catching" this exception in the function module.  By using the "exceptions" part of the function module, you are passing this exception back to the calling program.
    Regards,
    Rich Heilman

Maybe you are looking for

  • URGENT: Autonumber to use next AVAILABLE value

    Hi All I urgently need your help: I am writing a Java assignment using a MS Access database. Some of the columns are AutoNumber used as primary keys in a relationship. The program sometimes needs to delete records. The problem I have is that when I a

  • Cloning a prod database

    Suppose I have 2 databases, the prod is running on version 9.2.0.6 on a unix SunOS 5.8 and a test database running 9.2.0.6 on unix SunOS 5.8 (but a different physical box). The prod server has nightly hot backups and is in archive log mode. Requireme

  • Eject DVD script and map to eject key?

    Could someone instruct me on how to create an eject script to open my SuperDrive DVD tray and map it to the "Eject" key? I need a powerful programming solution here and I don't mind opening some sensitive system files if necessary. For some reason my

  • Indesign CS7 Cloud PMS conversion to cmyk

    Previous CS6 pms to cmyk conversion to get the same values as older versions CS5 and older, this was the work around: Adobe InDesign CS6: Quit the application From the folder Adobe InDesign CS6/Presets/Swatch Libraries/, remove all the libraries that

  • [WONTFIX] Having trouble with git clone for a VCS type PKGBUILD

    I'm trying to update (QGIS) in the AUR to use git so that I can make use of patches as they become available. I have source=("$pkgname"::'git+https://github.com/qgis/QGIS/tree/release-2_4') but this pulls a lot of data (750+ MB) and the pull or clone