Defensive programming vs exception handling

Hi
im new to java programming and having problems getting my head around defensive programming vs exception handling.
i've read in my uni books about design by contract and the idea of defensive programming but im having problems with it.
so say i write the code.
String container = //some value
if (container.equals.("")) // so if i am looking for a value and find a empty String
   throw new // a custom exception i have made for this error.
else
   //do whatever i had planned with a non-empty String
}is this Defensive programming or exception handling. Or am i complete of base.
thanks

jverd wrote:
JustSomeGuy wrote:
Don't fall into the trap of saying "Meh, the exception will handle it". If you can forsee something easily being a problem, and it can be controlled, then control it. Save the exception handling for those things you don't forsee and those you can't control. I disagree. Or at least, I disagree with what I think you're saying.
For instance, if null is not a valid argument, then document it, and don't waste code defending against it. Either throw an explicit IllegalArgumentException, or let the NPE be thrown.
And absolutely under no circumstances should you ever write code that will deliberately lead to an exception, Eh? If an exceptional condition occurs, you should delibrately throw an exception. Consider if you will the following code snippet
import java.io.*;
class ExceptionExample {
    public static void main(String[] args)
        throws IOException {
        if (args.length == 0) {
            System.out.println("Must give filename as first arg.");
            return;
        FileInputStream in;
        try {
            in = new FileInputStream(args[0]);
        catch (FileNotFoundException e) {
            System.out.println("Can't find file: " + args[0]);
            return;
        int ch;
        while ((ch = in.read()) != -1) {
            System.out.print((char) ch);
        System.out.println();
        in.close();
} What I was saying in the first part is shown with the following part of the above code
if (args.length == 0) {
   System.out.println("Must give filename as first arg.");
   return;
} Would the exception handler that follows this peice of code have taken care of that? Sure! Would it be the best choice to just let the exception handler do it? No way no how!
It is easy to forsee someone forgetting or not realizing they need to add the filename as an arg and it can be controlled, so in this and most cases just like it the best choice is to either inform the user with a more specific statement than could be used in the exceptionhandler and do nothing or fix it yourself like for instance by using a default filename.
What I meant by deliberately throwing an exception can be illustrated with this small portion of my code above
int ch;
while ((ch = in.read()) != -1) {
    System.out.print((char) ch);
} A -1 to mark the EOF is expected and reaching the EOF is expected. There is absolutely nothing abnormal about this, so it should not be handled by an exception. But far to often I have seen novice and especially "think they know it all novices" use an exception in place of exactly this. They know the file will end, they know they must do something about that, but instead of doing it right they just set it up so an exception will be thrown and they can just handle it in the exceptionhandler. This is what I meant by deliberately throwing exceptions, in that an exception must be thrown in order for their program to work as intended. Bad, very bad.
Now that I have provided an example and further clarified my position do you still disagree? I can't imagine you would, so if you do I would be very interested in getting some further insight into your reasoning.
JSG

Similar Messages

  • Exceptions Handling Programs Needed! Pls!!!

    Hi!
       Can any one give some sample programs of how exception handling is done in abap.
      Pls send it guys looking for your reply.
      [email protected]
       Rahul.

    Hi,
    Exceptions are situations that occur while an ABAP program is being executed, in which normal continuation of the program does not make any sense.
    Exceptions can be raised either implicitly in the ABAP runtime environment or explicitly in the ABAP program.
    For example, division by zero leads to an exception in the ABAP runtime environment. It is possible to determine this situation through a query in the ABAP program and to trigger an exception there.
    See the demo program DEMO_HANDLE_EXCEPTIONS in se38.
    *-------------------------------------EXAMPLE FOR RUNTIME ERROR---------------------------------------------------------------------------
    *DATA : VALUE1 TYPE I.
    *VALUE1 = 1 / 0. "------------->>>>>> IT MAKES RUN TIME ERROR.
    *WRITE : VALUE1.
    *---------------------------------EXAMPLE FOR HOW TO CATCH THE ARITHMETIC ERROR AT THE RUN TIME USING SUBRC---------------------------------
    *DATA : VALUE1 TYPE I.
    *CATCH SYSTEM-EXCEPTIONS ARITHMETIC_ERRORS = 1.
    *VALUE1 = 1 / 0.
    *WRITE : VALUE1.
    *ENDCATCH.
    *IF SY-SUBRC = 1.
    *WRITE : ' IT MAKES ERROR'.
    *ELSE.
    *WRITE : VALUE1.
    *ENDIF.
    in abap program we handle exceptions based on value returned by the system variable SY-SUBRC.
    if SY-SUBRC = 0.
    means execution completed sucessfull.
    if SY-SUBRC = 1........n.
    means execution compleated not sucessfully.
    if sy-sbrc = 0.
    write:/ 'execution sucessfull.
    **here write logic as per u r requirement
    else sy-subrc = '1'
    message
    elseif sy-subrc eq '2'
    message
    elseif sy-subrc eq '3'
    message
    elseif sy-subrc eq '4'
    message
    endif
    messages are defined in SE91..
    these messages are 5 types..
    A Termination Message
    The message appears in a dialog box, and the program terminates. When the user has confirmed the message, control returns to the next-highest area menu.
    <b>E Error Message</b>
    Depending on the program context, an error dialog appears or the program terminates.
    <b>I (nformation)<b>
    The message appears in a dialog box. Once the user has confirmed the message, the program continues immediately after the MESSAGE statement.
    <b>S(Status Message)<b>
    The program continues normally after the MESSAGE statement, and the message is displayed in the status bar of the next screen.
    <b>W(Warning)<b>
    Depending on the program context, an error dialog appears or the program terminates.
    <b>X(Exit)<b>
    No message is displayed, and the program terminates with a short dump. Program terminations with a short dump normally only occur when a runtime error occurs. Message type X allows you to force a program termination. The short dump contains the message ID.
    regards,
    Ashokreddy.

  • Exceptions vs defensive programming

    Hi...
    Which of the following two code fragments is 'better'... bearing in mind that Java's exception handling syntax is commonly touted as aiding readability, allowing programmers to focus on the 'task' rather than a nest of 'if' statements and suchlike? I'm just askin' outta interest's sake...
    Fragment 1...
    public void actionPerformed (final ActionEvent e) {
         if (_target != null && _clipboard != null) {
              Transferable clipContents = _clipboard.getContents (null);
              if (clipContents != null) {
                   if (clipContents.isDataFlavorSupported (DataFlavor.stringFlavor)) {
                        try {
                             String contents = (String) clipContents.getTransferData (DataFlavor.stringFlavor);
                             if (_target.getSelectedText () != null) {
                                  //replace the selection with the contents of the clipboard
                                  _target.replaceSelection (contents);
                             else {
                                  //insert the contents of the clipboard ahead of the current insertion point
                                  int insertionPoint = _target.getCaretPosition ();
                                  _target.getDocument ().insertString (insertionPoint, contents, null);
                        catch (final BadLocationException ble) {
                             //bleep! **((*!@4%@!! :D
                             Toolkit.getDefaultToolkit ().beep ();
                        catch (Exception ignoredForNow) {}
    }Fragment 2...
    public void actionPerformed (final ActionEvent e) {
         try {
              Transferable clipContents = _clipboard.getContents (null);
              if (clipContents.isDataFlavorSupported (DataFlavor.stringFlavor)) {
                   String contents = (String) clipContents.getTransferData (DataFlavor.stringFlavor);
                   if (_target.getSelectedText () != null) {
                        //replace the selection with the contents of the clipboard
                        _target.replaceSelection (contents);
                   else {
                        //insert the contents of the clipboard ahead of the current insertion point
                        int insertionPoint = _target.getCaretPosition ();
                        _target.getDocument ().insertString (insertionPoint, contents, null);
         catch (final BadLocationException ble) {
              //bleep! **((*!@4%@!! :D
              Toolkit.getDefaultToolkit ().beep ();
         catch (final NullPointerException npe) {
         catch (Exception ignoredForNow) {}     
    }

    I totally disagree with not having more than one return statement.
    I have had to maintain code like this and it is a total mess:
        boolean continue = true;
        int a = getSomeInfo();
        continue = someCheck(a);
        if (continue) {
            // do some stuff with a
            continue = someCondition();
        if (continue) {
           // do some other stuff with a
           continue = anotherCondition();
        //etc.
        return a;
    }The problem with this is really hard to detemine what gets returned when you try to read the code. I think the idea that one exit point in a function makes things more simple is total crap. Sometimes it is better but I'd rather see this.
        boolean continue = true;
        int a = getSomeInfo();
        if (someCheck(a)) return a;
        // do some stuff with a
        if  (someCondition()) return a
        // do some other stuff with a
        if (anotherCondition()) return a;
        //etc.
        return a;
    }This way you at least have the compiler on your side helping you make sure your conditions are reachable and so forth. Also, in any decent editor keywords like return are easy to spot and therefore are easier to see than a = something(). The idea of a single exit point was very valid before try catch finally, it helped make sure clean up was done. With finally you can forget that rule.
    Here's another good example where one exit point can be a pitfall.
    public String method(int value){
       String returnString;
       switch (value) {
          case 1:
             returnString = "one";
             break;
          case 2:
             returnString = "two";
          case 3:
             returnString = "three";
        return returnString;
    }There are two major problems with this code that may not be immediately obvious (more so in a more realistic and complicated example.) 1. If the value entered is not 1, 2 or 3 the method returns null (which you may or may not want.) 2. if the user enters 2 the result will be "three"
    Now if you use multiple returns both of these problem are non-existant
    public String method(int value){
       String returnString;
       switch (value) {
          case 1:
             return "one";
          case 2:
             String returnString = "two";
          case 3:
             return "three";
    }Problem 1 will now cause a compiler error because not all paths of the method return a value.
    Problem 2 will cause the same error because you are not returning anything for 2 and there is no return statement after the switch.

  • Is defensive programming out?

    Hi,
    I wondered if I am a naturally talented software tester, because on trying some random software I easily find ways to make it segfault.
    Two examples from today include rosegarden and kazehakase.
    rosegarden, default configuration:
    Start it, doubleclick on the first measure, choose menu "segment" -> "new layer", click the undo button, enjoy segfault.
    kazehakase, default configuration:
    Start it, choose menu "view" -> "ui level" -> "medium" or "expert", choose menu "view" -> "view page source" while no tab is open (as it is with default config on first start), enjoy segfault.
    So first kazehakase: Yes, I know it is a very early version. But I can live with missing functionality like "view page source" doing nothing. The problem is crashing on issueing such command. Without looking at the code I bet this is a null pointer (because there is no page displayed) of which the developer thought "oh, this probably won't ever be null".
    Next is rosegarden which wants to be "professional".
    I believe this bug with "undo" to be similar to the one in kolourpaint (start kolourpaint, choose text tool and write a letter, press strg+a, strg+z, this should be fixed, but at least now not in the repos.). Maybe it's a problem in qt in general or a problem with implementing "undo" in general. I don't care.
    When implementing an undo function I would be EXTREMELY careful to what happens in this functions.
    You have to be ready to undo ANYTHING that the user can possibly do in your program which is hell of a lot.
    In these programs people apparently didn't use defensive programming: I can see the programmer sitting there and think about how to undo several things but not how to handle something coming into his undo function that it cannot undo.
    I also believe plasma from KDE to crash so much instead of displaying an error message because of that.
    The question I ask myself is: Why do I see so many segfaults and so few error messages?
    Is it time for a kernel API to inform the application that it segfaulted and give it a chance to recover, maybe even with user intervention?
    Last edited by Cdh (2010-06-27 20:43:51)

    bernarcher wrote:
    I think defensive programming, even "simple" exception handling, never was widely used. It is by no means trivial and tends to bloat the code, esp. in languages with no exception handling mechanisms built in, like C for instance.
    Even using languages which do provide fairly good mechanisms for exception handling (like e.g. Eiffel, or D) it is difficult to catch edge cases in a meaningful way (other than simply finishing program execution). More often than not exceptions do not occur locally to the program part which really needs to handle the situation. And if they do they lead to more or less combinatorial explosion if not thoroughly planned. Thus, making a programm foolproof from start as "defensive programming" mandates is a tremendous effort (and not overly exciting to do).
    Even if you try to handle system signals, things tend to be involved and complicated. Just have a look at theSignal Concepts in the Open Group  Base Specification. Or have a look at man signal and related man pages.
    This is not to state defensive programming to be fruitless. But the efforts in time (and money) are most often not taken. You can't easily show built-in defenses. Being able to get a program "just running" and showing some effects appears far more exciting.
    It is like thorough testing (beyond running a unit test suite), and documenting (both software and user sides) - most desirable, but not many want to really do the works.
    Well said. I can't really elaborate on this but I'd have to wholeheartedly agree.
    (Sorry I can't elaborate I whenever i'm coding something thats one of the few things I try to look out for).
    Last edited by Ari'osika (2010-06-28 09:49:05)

  • 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

  • Exception handling in CE Visual Composer 7.1

    Hi,
    I have modeled a CAF Business Object and a custom Find operation which looks for a custom key. After that, I have exposed that operation as Web service and consumed it in Visual Composer. It is working perfectly as long as the search key exists in the Business Object backend table. When an arbitrart search term e.g. 1234 which does not exist is given, an error message is displayed and the program logic is halted.
    Error occured while executing the service: Error in connection: Could not execute Web service, consult your administrator
    My requirement is that, is it possible for me to display a custom message such as "The ID does not exist. Please enter a valid ID".
    Besides, is it possbile to bypass this service call if it is not working? In my scenario, this service is actually used to search for any existing data for a selected Customer. If there is no data, the user can proceed with a new definition. So, the above mentioned exception blocks the program flow and the user is not able to continue.
    Thanks in advance for any suggestions or ideas.
    Regards,
    Joon Meng

    I am not aware exception handling features of VC but instead of raising SOAP Fault you can also transfer log message which is user friendly to display.
    Another thing, instead of throwing exeption handle it inside try block so that program do not halt abruptly but gracefully. It is always possible to bypass existing service call like you said if output of service is not input of another.
    In other word do not map output directly but on the "Next" event of button which enable you to goto next screen to work.
    Regards,
    Gourav

  • Exception Handling in C++ generate core

    Hello ,
    I have a shared lib which is having some code for exception handling ,till the point of exception thrown program is running fine but after the exception get thrown the program is crasing and creating the core .
    I am using Solaris 5.9 on intel(x86) using compiler CC (CC: Sun C++ 5.5 2003/03/12 )
    I am specifing the Makefile here . If any one have faced the same kind of problem then please help me out.
    ***********************Makefile *****************************
    SHARED_LIBS = \
    /opt/SUNWspro/prod/lib/libp/libgc.a \
    /usr/lib/libCrun.so.1 \
    /opt/SUNWspro/prod/lib/CC4/libC.a \
    $(WLESSL)/lib/libgp.a \
    $(WLESSL)/lib/sslplus.a
    LIB=$(OBJ) $(SHARED_LIBS)
    LIB128=$(OBJ128) $(SHARED_LIBS)
    LIB_20=$(OBJ_20) $(SHARED_LIBS)
    CC_20=/opt/SUNWspro/bin/CC
    cc_20=/opt/SUNWspro/bin/cc
    CC_OUT_20=-w -KPIC -mt -lpthread -c $< -o $@
    # compile defintions
    DEF=-DAPACHE -DSOLARIS -DEAPI -D_POSIX_PTHREAD_SEMANTICS -D_PTHREAD -D_REENTRANT
    DOMFLAG=-DDOMESTIC_STRENGTH_ENABLED
    # this is not needed if apache20/bin/apxs is working properly
    APXS_CFLAGS_20=-mt -lpthread
    COMPILE=$(cc_20) $(APXS_CFLAGS_20) $(STD_20_INC) $(VER2) -c $(SRC) -o $(OBJDIR_20)/abc_w.o
    LOAD=$(cc_20) -G -z lazyload -o $(OBJDIR)/abc_wl_20.so $(LIB_20) $(OBJDIR_20)/abc.o
    LOAD128=$(cc_20) -G -o $(OBJDIR)/abc_wl128_20.so $(LIB128_20) $(OBJDIR_20)/abc.o
    # the DSO and objs should be placed in this directory
    OBJDIR=sol_x86
    OBJDIR_20=sol_x86/a20
    # WLE include files include tmmach which are platform specific
    WLESSLINC=$(WLESSL)/sysinclude

    Hi Santinu,
    I saw your question and thought of replying you, but I guess you might have got the solution by now as because the post date of your question is around a year back.
    You need to change $LOAD so that id uses CC instead of cc. There's a compatibility issue.
    LOAD=$(CC_20) -G -z lazyload -o $(OBJDIR)/mod_wl_20.so $(LIB_20) $(OBJDIR_20)/mod_weblogic.o
    LOAD128=$(CC_20) -G -o $(OBJDIR)/mod_wl128_20.so $(LIB128_20) $(OBJDIR_20)/mod_weblogic.o
    Hope this Helps.
    Thanks
    Somak

  • Exception handling in stored process, loop IF..ELSE

    Hello Guys,
    we want to put in exception handling in the loop but get the following error:
    Error(43,3): PLS-00103: Encountered the symbol "EXCEPTION" when expecting one of the following: begin case declare end exit for goto if loop mod null pragma raise return select update while with <an identifier> <a double-quoted delimited-identifier> <a bind variable> << close current delete fetch lock insert open rollback savepoint set sql execute commit forall merge pipe
    create or replace
    PROCEDURE xxxx
    FOR MESSSY IN
    select I.*
    FROM x I
    LOOP
    IF upper(CODE)='N' THEN
    INSERT INTO T_MESS(MP)
    select I.MP_ID
    FROM T_ME
    ELSIF upper(MESSSY.k2)='L' THEN
    DELETE T_MESS WHERE T_MESS.MP = MESSSY.MP;
    END IF;
    EXCEPTION
    WHEN DUP_VAL_ON_INDEX THEN
    A program attempted to insert duplicate values in a column that is constrained by a unique index.
    DBMS_OUTPUT.PUT_LINE ('A program attempted to insert duplicate values in a column that is constrained by a unique index.')
    --No Rollback
    END;
    COMMIT;
    END LOOP;
    END xxxx;
    does someone know why?

    BluShadow wrote:
    Well, your code is missing all sorts of bits and we don't have your data or your exact logic to know what it's supposed to be achieving.
    That is right, you dont have my data and that is why I was suprised by your comment.
    Since the input table might contain a few thousand rows and each of those might need to
    be considered N , D, or C and each case has a different handling I can not imagine how this
    can be all done with a merge statement.
    MERGE
    T_METRICPOINT_META with T_METRICSSYSTEM_LOAD where T_METRICSSYSTEM_LOAD .LOAD_DATE=to_char(sysdate)
    WHEN MATCHED THEN --we know those are the metric points that have to be loaded today, but we still need to do a IF..ELSE to handle them
    WHEN NOT MATCHED THEN -- not considered in todays load
    ----original code-----
    create or replace
    PROCEDURE myprocedure AS
    BEGIN
    --Extracting the records from T_METRICSSYSTEM_LOAD which have todays load date. Corresponding to these MP_System, we extract the MP_IDs from the T_METRICPOINT_META table.
    --Comapring these MP_IDs with the MP_IDs from the source(T_METRICPOINT_IMPORT) and extracting only those Metric points which need to be loaded today.
    FOR METRICSSYSTEM IN
    select I.*
    FROM T_METRICPOINT_IMPORT I
    where I.LOADDATE = TO_CHAR(SYSDATE) AND I.MP_ID IN
    (select a.MP_ID
    from T_METRICPOINT_META a INNER JOIN T_METRICSSYSTEM_LOAD b on a.MP_SYSTEM = b.MP_SYSTEM where b.LOAD_DATE=to_char(sysdate))
    LOOP
    --If mutation code in the source/import data is "N", the record is inserted as it is in the "T_METRICPOINTS" table.
    IF upper(METRICSSYSTEM.MUTATIONCODE)='N' THEN --new
    INSERT INTO T_METRICPOINTS(MP_ID, ......)
    SELECT DISTINCT I.MP_ID,.....
    FROM T_METRICPOINT_IMPORT I WHERE I.MP_ID = METRICSSYSTEM.MP_ID
    ELSIF upper(METRICSSYSTEM.MUTATIONCODE)='D' THEN --delete
    DELETE T_METRICPOINTS WHERE T_METRICPOINTS.MP_ID = METRICSSYSTEM.MP_ID AND T_METRICPOINTS.KEY = METRICSSYSTEM.KEY;
    ELSIF upper(METRICSSYSTEM.MUTATIONCODE)='C' THEN --correction
    UPDATE T_HISTORYMETRICPOINTS H
    SET CHANGE_DATE = to_char(sysdate)
    WHERE H.MP_ID=METRICSSYSTEM.MP_ID AND H.KEY = METRICSSYSTEM.KEY;
    INSERT INTO T_HISTORYMETRICPOINTS(MP_ID, KEY, .....)
    --The distinct here is used, to handle 2 identical records in the input table with correction value "C". This would insert into 1 record in the T_HISTORYMETRICPOINTS table without
    --violating the primary key constraint.
    select DISTINCT I.MP_ID,I.KEY, ....
    FROM T_METRICPOINT_IMPORT I WHERE I.MP_ID = METRICSSYSTEM.MP_ID
    --END IF;
    END IF;
    COMMIT;
    END LOOP;
    END myprocedure;

  • Removing Exception Handling Causes Compiler Error

    I am very new to Java. I have a background in other programming languages including Ruby. I am in need of a convenient means to parse XML code. I picked up the code shown at the end of this message on the Internet. In its original form, it works perfectly. I experimented by trying to comment out the try block as you can see. I was surprised to find that in that form it wouldn't compile. In essence, I thought what I was doing was simply removing exception handling. I figured that since the code worked and there were no exceptions being thrown, it would work just fine for experimentation purposes. (I understand that I would not want to do this in production mode.) Can someone please explain to me why removing the exception handling causes the program to fail to compile?
    Thanks for any input.
    ... doug
    /* Experimental Code */
    /* http://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/ */
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.DocumentBuilder;
    import org.w3c.dom.Document;
    import org.w3c.dom.NodeList;
    import org.w3c.dom.Node;
    import org.w3c.dom.Element;
    import java.io.File;
    public class ReadXMLFile {
    public static void main(String argv[]) {
    try {
    File fXmlFile = new File("ReadXMLFile.xml");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fXmlFile);
    doc.getDocumentElement().normalize();
    System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
    NodeList nList = doc.getElementsByTagName("staff");
    System.out.println("-----------------------");
    for (int temp = 0; temp < nList.getLength(); temp++) {
    Node nNode = nList.item(temp);     
    if (nNode.getNodeType() == Node.ELEMENT_NODE) {
    Element eElement = (Element) nNode;
    System.out.println("First Name : " + getTagValue("firstname",eElement));
    System.out.println("Last Name : " + getTagValue("lastname",eElement));
    System.out.println("Nick Name : " + getTagValue("nickname",eElement));
    System.out.println("Salary : " + getTagValue("salary",eElement));
    } catch (Exception e) {
    e.printStackTrace();
    private static String getTagValue(String sTag, Element eElement){
    NodeList nlList= eElement.getElementsByTagName(sTag).item(0).getChildNodes();
    Node nValue = (Node) nlList.item(0);
    return nValue.getNodeValue();
    }

    877757 wrote:
    I figured that since the code worked and there were no exceptions being thrown, it would work just fine for experimentation purposes. The compiler doesn't know that your code works. It only knows that some method you call can throw some checked exception, and it requires you to catch it or declare that you don't.

  • BPM Exception Handling

    I am trying to test my Deadline and Exception handling.But it is not at all working. I will explain what I have done, please guide me where I am going wrong.
    1) Block Step. Properties --- Exception == ERROR1
    2)Switch Step . Success Branch . Send Step. with a Transport Response. And I am sending to the Mail adapter. And in directory I have provided the WRONG URL FOR THIS Mail.
          Otherwsie Branch. Send step, sending to a File.
    3)Dead Lock Branch : Having a Control Step.
                  Properties
                   Action : Throw Exception
                   Exception: ERROR1
    4) Exception Branch.
               Properties
                    Exception Handler : ERROR1
          Send Step : Send a Message to  a File (
    Result
    I am Seeing a Clock in my SXMB_MONI OUTBOUND_Status column, because I am expecting a TRANSPOT Response, and this going to never happen, so I thought the Deadline monitor will wakeup after 1 minute interval and my Exception branch has to Trigger, but it has never triggered my Deadline branch aswell as my Exception Branch.
    WE are in XI SP 12.  We dont have CCMS installed yet, even ALERT management is not installed.
    Please guide me.
    Thanks.

    Hi Anand,
    I looked into the Transaction SWI2_DEAD and I dont see any listings there.
    I am executing 1 Minute deadline Monitoring and from here firing an exception Branch, for my Asynchronous Scenario.
    So definitely after a minute , the DeadLine Branch should have been fired. But it didnot take place.
    In the mean time I have located an OSS notes OSS note 829921 And I am awaiting my Basis team to apply this note.
    symptom
    If the execution of an asynchronous method ends with a "system error" or "application error", the work item is not set to the 'ERROR' status.
    Other terms
    Reason and Prerequisites
    This problem is caused by a program error.
    Solution
    Implement the correction instructions.
    Note the following manual changes that must be implemented BEFORE you use SNOTE to implement the corrections:
    1. Make sure that the SET_EXECUTION_INTERRUPTED method of the CL_SWF_RUN_RESULT class has the following parameters:
    a) IM_CODE, Importing, Optional, Type SWO_RETURN, default Value 0000
    b) IM_ERRORTYPE, Importing, Optional, Type SWO_ERRTYP, Default Value 0
    Note the following manual changes, which you must carry out AFTER you have implemented the corrections:
    1. The M_EXECUTION_INTERRUPTED attribute type of the CL_SWF_RUN_RESULT class must be changed to EXECUTION_INTERRUPTED.

  • Never implemented exception handling  in Stored Procedures

    I have lots of stand alone stored procedures callled from .NET 20 programs that follow the following pattern. They runn against Oracle 10.2 on Win2003. The only deviiation is a couple where I insert to temptables. I specify a parameter for messages but don't know the best way to implement for Oracle as well as any tips on ODP.NET/oracle interactions error handling.
    1. Is it recommended to implement exception handling in With Clauses?
    2. If there is an exception in one cursor's SQL, how do I still execute the second?
    3. Is it best in some circumstances to pass a null back to client and check for null in program?
    From .NET programs I have run into a couple of problems.
    4. TNS packet failure.
    Anyways any suggestions or experiences are welcome.
    CREATE OR REPLACE  PROCEDURE   GET_SALES_DATA
                      ,   p_businessdate      in   date                 
                      ,   p_message         out varchar2     
                      ,   p_rcSales             out sys_refcursor
                      ,   p_rInventory            out sys_refcursor
    ) is
    open p_rcSales for
    with somedata as (select ...)
    , someMoreData as (selct ...)
    -- Main select
    Select * from somedata sd inner join somemoredata  smd on smd.key   = sd.key;
    open p_rcInventory for
    with somedata as (select ...)
    , someMoreData as (selct ...)
    -- Main select
    Select * from somedata sd inner join somemoredata  smd on smd.key   = sd.key;
    -- CODE NOT IMPLEMENTED
    -- exception 
    -- when TOO_MANY_ROWS  then  select 'Error handling for future implementations' into p_message from dual ;
    -- when NO_DATA_FOUND  then  select 'Error handling for future implementations. No data'  into p_message from dual;
    -- when others         then  raise_application_error(-20011,'Unknown Exception in GET_SALES_DATA Function');
    -- WHEN invalid_business_date then  select 'Invalid: Business date is in the current work week.' into p_message from dual ;
    END GET_SALES_DATA;Pseudocode'ish because Module level variables and properties have not been defined here for brevity.
    Public Class WebPage1
    PAge_Load
       GetData
    End Class Data Access Layer
    Public Class DAL
    Public Sub GetOracleData()
                Dim conn As OracleConnection
                    Try
                        conn = New OracleConnection
                    Catch ex As Exception
                        Throw ex
                    End Try
                    Dim cmd As New OracleCommand
                    With cmd
                        conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("MyConnectionString").ToString
                        cmd.CommandText = DATABASE.GetSalesData
                        cmd.CommandType = CommandType.StoredProcedure
                        cmd.Connection = conn
                    End With
                    cmd.Connection = conn
                    Dim oparam As OracleParameter
                    oparam = cmd.Parameters.Add("p_businessdate", OracleDbType.Date)
                    oparam.Value = BusinessDate.ToString("dd-MMM-yy")
                    oparam = cmd.Parameters.Add("p_message", OracleDbType.Varchar2, ParameterDirection.Output)
                    oparam = cmd.Parameters.Add("p_rc_inven_csv", OracleDbType.RefCursor, ParameterDirection.Output)
                    oparam = cmd.Parameters.Add("p_rcSales", OracleDbType.RefCursor, ParameterDirection.Output)
                    oparam = cmd.Parameters.Add("p_rcInventory", OracleDbType.RefCursor, ParameterDirection.Output)
                    Dim Adapter As New OracleDataAdapter(cmd)
                    Try
                        Adapter.TableMappings.Add("Table", Sales)
                        Adapter.TableMappings.Add("Table1", Inventory)              
                        Adapter.Fill(dsOracleData)
                    Catch ex As OracleException
                        HandleError("Exception Retrieving Oracle Data", ex, MethodInfo.GetCurrentMethod.Name, True)
                     Finally
                        If conn.State = ConnectionState.Open Then
                            conn.Close()
                        End If
                    End Try
                    dbMessages = cmd.Parameters("p_message").ToString
                End If
                arrStatusMessages.Add("Retrieved Oracle Data Successfully")
            End Sub
           ' Original Implementation ; No longer used
            Public function GetOracleData
               Dim conn As New OracleConnection
                conn.ConnectionString = dbconn.Connectionstring
                 Dim cmd As New OracleCommand
                    With cmd
                        conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("MyConnectionString").ToString
                        cmd.CommandText = DATABASE.GetSalesData
                        cmd.CommandType = CommandType.StoredProcedure
                        cmd.Connection = conn
                    End With
                    cmd.Connection = conn
                    Dim oparam As OracleParameter
                    oparam = cmd.Parameters.Add("p_businessdate", OracleDbType.Date)
                    oparam.Value = BusinessDate.ToString("dd-MMM-yy")
                    oparam = cmd.Parameters.Add("p_message", OracleDbType.Varchar2, ParameterDirection.Output)
                                 oparam = cmd.Parameters.Add("p_rcSales", OracleDbType.RefCursor, ParameterDirection.Output)
                    oparam = cmd.Parameters.Add("p_rcInventory", OracleDbType.RefCursor, ParameterDirection.Output)
                    Dim Adapter As New OracleDataAdapter(cmd)
                    Try
                        Adapter.TableMappings.Add("Table", Sales)
                        Adapter.TableMappings.Add("Table1", Inventory)              
                        Adapter.Fill(dsOracleData)
                    dim dt as datatable = dsoracledata.tables("sales")
                    If IsDataNull(dt) Then
                         _errorType = DBErrorType.NullData
                    End If
                    If isDataEmpty(dt) Then
                         _errorType = DBErrorType.EmptyData
                    End If
                    _hasError = False
                Catch oraEx As OracleException
                      _ExceptionText = oraEx.Message.ToString
                    _errorType = DBErrorType.OracleException
    #If DEBUG Then
                    Throw oraEx
    #End If
                Catch zeroEx As DivideByZeroException
                    _ExceptionText = zeroEx.Message.ToString
                    _errorType = DBErrorType.DivideByZeroException
    #If DEBUG Then
                    Throw zeroEx
    #End If
                Catch oflowEx As OverflowException
                    _ExceptionText = oflowEx.Message.ToString
                    _errorType = DBErrorType.OverflowException
    #If DEBUG Then
                    Throw oflowEx
    #End If
                Catch argEx As InsufficientMemoryException
                    _ExceptionText = argEx.Message.ToString
                    _errorType = DBErrorType.InsufficientMemoryException
    #If DEBUG Then
                    Throw argEx
    #End If
                Catch nomemEx As OutOfMemoryException
                    _ExceptionText = nomemEx.Message.ToString
                    _errorType = DBErrorType.OutOfMemoryException
    #If DEBUG Then
                    Throw nomemEx
    #End If
                Catch Ex As Exception
                    _ExceptionText = Ex.Message.ToString
                    _errorType = DBErrorType.GenericException
    #If DEBUG Then
                    Throw Ex
    #End If
                Finally
                    If conn.State = ConnectionState.Open Then
                        conn.Close()
                    End If
                End Try
    End class Error Class
    Public Class Errors
           Public Sub ExitClass()
                Return
            End Sub
            ' 'blnWriteNow says when Error is critical and no further processing needs to be done by class, then write to event logs or text files and call exit class
            '  to return control back to webpage. This is my first time trying this way.
            Public Sub HandleError(ByVal friendlyMsg As String, ByVal objEx As Exception, ByVal methodInfo As String, Optional ByVal blnWriteNow As Boolean = False)
                If Not blnWriteNow Then Exit Sub
                Dim strMessages As String
                strMessages = arrStatusMessages
                'Send error email
                If  blnSendEmails Then
                     SendMail("[email protected],  strMessages. applicationname, " has thrown  error. ")
                End If
              'Throw error for   debugging
                If  blnThrowErrors Then  
                            Throw New Exception(strMessages & vbCrLf & objEx.Message)
                End If
               ' Write to event log and if not available (shared hosting environment), write to text log
                If blnWriteNow Then
                    If  blnWriteToEvtLog Then
                        If  blnCanWriteToEvtLog Then    'Program has write permission to log
                             WriteToEventLog(strMessages, _appname, EventLogEntryType.Error,  appname)
                        Else
                            If Not Directory.Exists( appPath & "\log") Then
                                Try
                                    Directory.CreateDirectory( appPath & "\log")
                                Catch ex As Exception
                                    arrStatusMessages.Add("Cant't write to event log or create a directory")
                                End Try
                            End If
                        End If
                    End If
                End If          
            End Sub
    End Class

    I have lots of stand alone stored procedures callled from .NET 20 programs that follow the following pattern. They runn against Oracle 10.2 on Win2003. The only deviiation is a couple where I insert to temptables. I specify a parameter for messages but don't know the best way to implement for Oracle as well as any tips on ODP.NET/oracle interactions error handling.
    1. Is it recommended to implement exception handling in With Clauses?
    2. If there is an exception in one cursor's SQL, how do I still execute the second?
    3. Is it best in some circumstances to pass a null back to client and check for null in program?
    From .NET programs I have run into a couple of problems.
    4. TNS packet failure.
    Anyways any suggestions or experiences are welcome.
    CREATE OR REPLACE  PROCEDURE   GET_SALES_DATA
                      ,   p_businessdate      in   date                 
                      ,   p_message         out varchar2     
                      ,   p_rcSales             out sys_refcursor
                      ,   p_rInventory            out sys_refcursor
    ) is
    open p_rcSales for
    with somedata as (select ...)
    , someMoreData as (selct ...)
    -- Main select
    Select * from somedata sd inner join somemoredata  smd on smd.key   = sd.key;
    open p_rcInventory for
    with somedata as (select ...)
    , someMoreData as (selct ...)
    -- Main select
    Select * from somedata sd inner join somemoredata  smd on smd.key   = sd.key;
    -- CODE NOT IMPLEMENTED
    -- exception 
    -- when TOO_MANY_ROWS  then  select 'Error handling for future implementations' into p_message from dual ;
    -- when NO_DATA_FOUND  then  select 'Error handling for future implementations. No data'  into p_message from dual;
    -- when others         then  raise_application_error(-20011,'Unknown Exception in GET_SALES_DATA Function');
    -- WHEN invalid_business_date then  select 'Invalid: Business date is in the current work week.' into p_message from dual ;
    END GET_SALES_DATA;Pseudocode'ish because Module level variables and properties have not been defined here for brevity.
    Public Class WebPage1
    PAge_Load
       GetData
    End Class Data Access Layer
    Public Class DAL
    Public Sub GetOracleData()
                Dim conn As OracleConnection
                    Try
                        conn = New OracleConnection
                    Catch ex As Exception
                        Throw ex
                    End Try
                    Dim cmd As New OracleCommand
                    With cmd
                        conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("MyConnectionString").ToString
                        cmd.CommandText = DATABASE.GetSalesData
                        cmd.CommandType = CommandType.StoredProcedure
                        cmd.Connection = conn
                    End With
                    cmd.Connection = conn
                    Dim oparam As OracleParameter
                    oparam = cmd.Parameters.Add("p_businessdate", OracleDbType.Date)
                    oparam.Value = BusinessDate.ToString("dd-MMM-yy")
                    oparam = cmd.Parameters.Add("p_message", OracleDbType.Varchar2, ParameterDirection.Output)
                    oparam = cmd.Parameters.Add("p_rc_inven_csv", OracleDbType.RefCursor, ParameterDirection.Output)
                    oparam = cmd.Parameters.Add("p_rcSales", OracleDbType.RefCursor, ParameterDirection.Output)
                    oparam = cmd.Parameters.Add("p_rcInventory", OracleDbType.RefCursor, ParameterDirection.Output)
                    Dim Adapter As New OracleDataAdapter(cmd)
                    Try
                        Adapter.TableMappings.Add("Table", Sales)
                        Adapter.TableMappings.Add("Table1", Inventory)              
                        Adapter.Fill(dsOracleData)
                    Catch ex As OracleException
                        HandleError("Exception Retrieving Oracle Data", ex, MethodInfo.GetCurrentMethod.Name, True)
                     Finally
                        If conn.State = ConnectionState.Open Then
                            conn.Close()
                        End If
                    End Try
                    dbMessages = cmd.Parameters("p_message").ToString
                End If
                arrStatusMessages.Add("Retrieved Oracle Data Successfully")
            End Sub
           ' Original Implementation ; No longer used
            Public function GetOracleData
               Dim conn As New OracleConnection
                conn.ConnectionString = dbconn.Connectionstring
                 Dim cmd As New OracleCommand
                    With cmd
                        conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("MyConnectionString").ToString
                        cmd.CommandText = DATABASE.GetSalesData
                        cmd.CommandType = CommandType.StoredProcedure
                        cmd.Connection = conn
                    End With
                    cmd.Connection = conn
                    Dim oparam As OracleParameter
                    oparam = cmd.Parameters.Add("p_businessdate", OracleDbType.Date)
                    oparam.Value = BusinessDate.ToString("dd-MMM-yy")
                    oparam = cmd.Parameters.Add("p_message", OracleDbType.Varchar2, ParameterDirection.Output)
                                 oparam = cmd.Parameters.Add("p_rcSales", OracleDbType.RefCursor, ParameterDirection.Output)
                    oparam = cmd.Parameters.Add("p_rcInventory", OracleDbType.RefCursor, ParameterDirection.Output)
                    Dim Adapter As New OracleDataAdapter(cmd)
                    Try
                        Adapter.TableMappings.Add("Table", Sales)
                        Adapter.TableMappings.Add("Table1", Inventory)              
                        Adapter.Fill(dsOracleData)
                    dim dt as datatable = dsoracledata.tables("sales")
                    If IsDataNull(dt) Then
                         _errorType = DBErrorType.NullData
                    End If
                    If isDataEmpty(dt) Then
                         _errorType = DBErrorType.EmptyData
                    End If
                    _hasError = False
                Catch oraEx As OracleException
                      _ExceptionText = oraEx.Message.ToString
                    _errorType = DBErrorType.OracleException
    #If DEBUG Then
                    Throw oraEx
    #End If
                Catch zeroEx As DivideByZeroException
                    _ExceptionText = zeroEx.Message.ToString
                    _errorType = DBErrorType.DivideByZeroException
    #If DEBUG Then
                    Throw zeroEx
    #End If
                Catch oflowEx As OverflowException
                    _ExceptionText = oflowEx.Message.ToString
                    _errorType = DBErrorType.OverflowException
    #If DEBUG Then
                    Throw oflowEx
    #End If
                Catch argEx As InsufficientMemoryException
                    _ExceptionText = argEx.Message.ToString
                    _errorType = DBErrorType.InsufficientMemoryException
    #If DEBUG Then
                    Throw argEx
    #End If
                Catch nomemEx As OutOfMemoryException
                    _ExceptionText = nomemEx.Message.ToString
                    _errorType = DBErrorType.OutOfMemoryException
    #If DEBUG Then
                    Throw nomemEx
    #End If
                Catch Ex As Exception
                    _ExceptionText = Ex.Message.ToString
                    _errorType = DBErrorType.GenericException
    #If DEBUG Then
                    Throw Ex
    #End If
                Finally
                    If conn.State = ConnectionState.Open Then
                        conn.Close()
                    End If
                End Try
    End class Error Class
    Public Class Errors
           Public Sub ExitClass()
                Return
            End Sub
            ' 'blnWriteNow says when Error is critical and no further processing needs to be done by class, then write to event logs or text files and call exit class
            '  to return control back to webpage. This is my first time trying this way.
            Public Sub HandleError(ByVal friendlyMsg As String, ByVal objEx As Exception, ByVal methodInfo As String, Optional ByVal blnWriteNow As Boolean = False)
                If Not blnWriteNow Then Exit Sub
                Dim strMessages As String
                strMessages = arrStatusMessages
                'Send error email
                If  blnSendEmails Then
                     SendMail("[email protected],  strMessages. applicationname, " has thrown  error. ")
                End If
              'Throw error for   debugging
                If  blnThrowErrors Then  
                            Throw New Exception(strMessages & vbCrLf & objEx.Message)
                End If
               ' Write to event log and if not available (shared hosting environment), write to text log
                If blnWriteNow Then
                    If  blnWriteToEvtLog Then
                        If  blnCanWriteToEvtLog Then    'Program has write permission to log
                             WriteToEventLog(strMessages, _appname, EventLogEntryType.Error,  appname)
                        Else
                            If Not Directory.Exists( appPath & "\log") Then
                                Try
                                    Directory.CreateDirectory( appPath & "\log")
                                Catch ex As Exception
                                    arrStatusMessages.Add("Cant't write to event log or create a directory")
                                End Try
                            End If
                        End If
                    End If
                End If          
            End Sub
    End Class

  • UTL file exception handling oracle 11g

    We use oracle 11g
    We use UTL file and exception handling in many place. Thanks in advance.
    We have many utl program and we are writing same exception handling code ,copy and paste .
    It is possible to create new UTL exception procedure and call it.
    I am not sure how to write generic UTL exception procedure and reuse the same.
    I am learning oracle etl files method.
    Please advise.
    sample program 1 :
    DECLARE
    fileHandler UTL_FILE.FILE_TYPE;
    BEGIN
    fileHandler := UTL_FILE.FOPEN('test_dir', 'test_file.txt', 'W');
    UTL_FILE.PUTF(fileHandler, 'Writing TO a file\n');
    UTL_FILE.FCLOSE(fileHandler);
    EXCEPTION
    when utl_file.invalid_path then
    raise_application_error(-20001,
    'INVALID_PATH: File location or filename was invalid.');
    when utl_file.invalid_mode then
    raise_application_error(-20002,
    'INVALID_MODE: The open_mode parameter in FOPEN was invalid.');
    when utl_file.invalid_filehandle then
    raise_application_error(-20002,
    'INVALID_FILEHANDLE: The file handle was invalid.');
    when utl_file.invalid_operation then
    raise_application_error(-20003,
    'INVALID_OPERATION: The file could not be opened or operated on as requested.');
    when utl_file.read_error then
    raise_application_error(-20004,
    'READ_ERROR: An operating system error occurred during the read operation.');
    when utl_file.write_error then
    raise_application_error(-20005,
    'WRITE_ERROR: An operating system error occurred during the write operation.');
    when utl_file.internal_error then
    raise_application_error(-20006,
    'INTERNAL_ERROR: An unspecified error in PL/SQL.');
    when utl_file.invalid_filename then
    raise_application_error(-20010, 'The filename parameter is invalid.');
    WHEN OTHERS THEN
    IF UTL_FILE.IS_OPEN(fileHandler ) THEN
    UTL_FILE.FCLOSE (fileHandler );
    END IF;
    RAISE;
    END;
    How to write generic procedure of utl exception handling ?
    please advise.
    create or replace procedure sp_utl_exception
    begin
    when utl_file.invalid_path then
    raise_application_error(-20001,
    'INVALID_PATH: File location or filename was invalid.');
    when utl_file.invalid_mode then
    raise_application_error(-20002,
    'INVALID_MODE: The open_mode parameter in FOPEN was invalid.');
    when utl_file.invalid_filehandle then
    raise_application_error(-20002,
    'INVALID_FILEHANDLE: The file handle was invalid.');
    when utl_file.invalid_operation then
    raise_application_error(-20003,
    'INVALID_OPERATION: The file could not be opened or operated on as requested.');
    when utl_file.read_error then
    raise_application_error(-20004,
    'READ_ERROR: An operating system error occurred during the read operation.');
    when utl_file.write_error then
    raise_application_error(-20005,
    'WRITE_ERROR: An operating system error occurred during the write operation.');
    when utl_file.internal_error then
    raise_application_error(-20006,
    'INTERNAL_ERROR: An unspecified error in PL/SQL.');
    when utl_file.invalid_filename then
    raise_application_error(-20010, 'The filename parameter is invalid.');
    WHEN OTHERS THEN
    IF UTL_FILE.IS_OPEN(fileHandler ) THEN
    UTL_FILE.FCLOSE (fileHandler );
    END IF;
    RAISE;
    end;

    Mahesh Kaila wrote:
    Hello,
    Common procedure to log exception in log file
    create or replace procedure sp_utl_exception (log_dir varchar2, log_file varchar2, exception_msg varchar2)
    is
    hnd_file   UTL_FILE.file_type;
    begin
    hnd_file := UTL_FILE.fopen (log_dir, log_file, 'A');
    UTL_FILE.put_line (hnd_file, exception_msg);
    UTL_FILE.fclose (hnd_file);
    exception
    when others
    then
    raise;
    end;
    Very poor implementation.
    a) Absolutely no need for that exception handler in there. It should be removed.
    b) As it's a procedure for logging exceptions relating to UTL_FILE, it would seem error prone to be logging the errors with UTL_FILE. For example, what is it supposed to do if the exception is raised because of lack of disk space in those file locations? How is it going to write out the exception with the disk full? Also, if the exception handler is used by multiple processes, then only 1 process at a time can access the log file to write it's exceptions, so it doesn't scale well. Better logging is done by having an autonomous transaction procedure that writes log/trace messages to dedicated table(s). That also means that the logs etc. can be viewed, as appropriate, from any client using SQL (either manually or through a application written to view logs etc.), rather than requiring physical/remote access to the server o/s to go and view the contents of the file, which in itself could lock the file and prevent any process from writing further logs whilst it's being used.

  • Is Exception Handling  in every Java code?

    Hi there,
    just curious, is including exception handling the "norm" for any Java code?

    Java divide the exception handling in two kinds :
    - exceptions which need to be programatically handled
    - exceptions which are automatically handled by Java such as ArrayIndexOutOfBounds, DivisionByZero, and lot of subclasses of RuntimeException.
    It's not because they are automatically handled that you can't handle them programatically, but programming will be too difficult and long if they wasn't handled automatically.
    Exception mechanism is very powerfull but a little bit long when an exception is thrown.
    Denis

  • RFC: Exception handling

    Hi there,
    after playing a bit with external xml files provided by my
    application i'm ready to go to the next topic on my ToDo-List.
    How could one implement a good and stable technique for
    exception handling? I'm talking about the interaction from spry to
    our Web Framework which throws an error sometimes.
    My current idea is that the server side framework could
    return some kind of Error XML format which contains the exception
    message and so on. This would require functions on client side to
    precheck the server output.
    Imho the best place for this is inside the XMLDataSet
    constructor. When catching some bad XML file internal error
    messages could be send using the already existing techniques OR by
    providing an public function which then should be overriden by an
    selfwritten one, e.g. to put it into my own `error box`.
    Also, some kind of internal statemachine in XMLDataSet may
    help a lot. That way each access to functions which aren't working
    at the moment could be loggend and catched by an selfwritten
    function.
    I hope you get the idea,
    what do you think?
    Best regards,
    Sebastian

    Better error handling and error handling hooks is on the list
    of things to do.
    The way I see it, there are several types of errors that can
    occur:
    1. Server returns valid XML, but it's XML that describes an
    error instead of the data requested.
    - I believe this is what Sebastian was mentioning. I was
    actually thinking of allowing a hook for developers to catch and
    handle this case and perhaps leverage the states mechanism to let
    them change the dynamic region markup used to display the error
    since the data references in this error XML would be different.
    2. The server returns an error. (Invalid URL or Server Error)
    - This could be handled with states, but we need to expose
    some data references, or set the data set to contain a known data
    set schema that would allow the designer to show more info about
    the error.
    3. The server returns XML but uses a mime-type that is not
    understood by Spy or the XML parsing code built-into the browser.
    - I believe it was Doug [?] that had a patch that *always*
    forced the data set to try and parse the XML string in the response
    if the response didn't contain an XML DOM. My one paranoia about
    that is that the server could actually be returning something that
    is not XML, in which we would still fail and perhaps choke
    somewhere else. I need to do some testing in that area.
    I was thinking perhaps we should add something to the
    XMLDataSet constructor that allowed a user to specify mime-types
    for formats they knew were XML, but didn't use one of the standard
    XML formats.
    4. The browser chokes on "not-well-formed" XML.
    - This is an interesting problem. IE silently fails when the
    parser chokes, but Mozilla creates an XML DOM tree that reports the
    error which does *not* match the XML string from the request
    response. I had to add code to spry to detect when this happens.
    5. An exception is thrown during Spry processing of XML data.
    - This will require more programming on our part to handle
    more cases.
    --== Kin ==--

  • Console Exception Handling.  Allow another attempt for user before exiting

    I am trying to implement a very simple program that prompts the user for info and reads in a few numbers. If the user accidentally enters a letter instead of a number I want the user to get another chance, not just execute the exception handler and exit the program (as it does now). I'd rather have the user get stuck in an endless loop waiting for valid input versus exiting on the first invalid entry.
    The code I am using is something like this:
    try{
       System.out.println("Enter a number?");
       int b=System.in.read();
       char c=(char) b;
       String s=String.valueOf(c);
       p.setDummyValue(Integer.parseInt(s) ); //**Possible Exception Here
    catch(NumberFormatException e) {
       System.out.println("Invalid Input");
       // *** I'd love to somehow return to the "Enter a number" line from here
    catch(IOException e) {
       //IO error code here
    }Q: How can I implement the ability to allow a user to correct invalid input?
    Thanks

    Something like this should work:boolean numberValid = false;
    while (!numberValid) {
         try {
              System.out.println("Enter a number?");
              int b=System.in.read();
              System.in.skip(System.in.available()); // skip carriage return
              char c=(char) b;
              String s=String.valueOf(c);
              p.setDummyValue(Integer.parseInt(s));
              numberValid = true;
         } catch(NumberFormatException e) {
              System.out.println("Invalid Input");
         } catch(IOException e) {
              //IO error code here
    }

Maybe you are looking for

  • Mac Pro will not sleep

    As requested, this is a new post from the "my mac will not wake up" thread. I am having trouble putting my Mac to sleep. When I try to enter sleep mode, the fans make noise like it wants to restart, then the monitors go out and immediately back on. I

  • Restoring Preferences & Settings after Lion Re-Install

    For reasons I regret I decided to re-install Lion, thinking that it might resolve a problem I was having with mail. It was interesting to go through the new process, using the Lion partition set aside on your hard drive... since there are no longer a

  • Nokia PC Suite 6 84 10 3 eng web.exe crashes on wi...

    See the attached picture. look like somebody is trying to delete a NULL pointer. additional note: it was already a pain installing the software in the first place

  • Usage Descision tables

    Hi all How is the relation built in tables for a material with  its QM Usage descision. where QM  descisions stored for a material. sri

  • Urgent question about following referrals manually (not automatically)

    I have a crucial question on the following code from the sun tutorial, for following referrals manually. The question is below the code: ================= // Set the referral property to throw ReferralException env.put(Context.REFERRAL, "throw"); //