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.

Similar Messages

  • Is Exception handler necessary for every stored subprogram

    Hi All,
    I knwo exception handler is very important. But is it necessary for every stored procedure or function?
    For example,
    procedure test(p_index_code IN varchar2(10)
    p_changed_code OUT varchar2(15))
    as
    begin
    IF p_index_code = 'A' then
    p_changed_code := 'A'|| p_index_code;
    elsif p_index_code = 'B' then
    p_changed_code := 'B'|| p_index_code;
    else
    p_changed_code := p_index_code;
    end if;
    end;
    This kind of simple procedures, do I have to add the 'exection when others than raise_application_error(-20001,'error in this SP')'?
    I can't see obvious drawbacks without the exception handler in this CASE.
    Best regards,
    Leon
    Edited by: user12064076 on Nov 11, 2010 7:12 PM

    user12064076 wrote:
    I knwo exception handler is very important. But is it necessary for every stored procedure or function?It is important to know WHY an exception handler is needed. There are couple of basic reasons why you want to use an exception handler.
    The exception is not an error.
    The exception raised is a technical error, but may not be a business or processing error. The typical example is the NO_DATA_FOUND exception. The business logic may say "+when there is no fixed discounts found, apply a 5% dis-count+". So not finding (dis-count) row data in such a case is not an exception. What does you exception handler do? It fixes the exception and there is not an exception anymore. In other words, the caller that called your code will never know that there was an exception.
    Making the exception meaningful
    An exception, like NO_DATA_FOUND, is not very meaningful. What is meaningful is NO_INVOICE_FOUND or NO_CUSTOMER_FOUND. Thus your exception handler can catch a generic exception and make it more meaningful by returning a custom application exception instead.
    Action stations
    Some exceptions will require you to clean up and fix what you can - kind of like action stations when a ship takes a hit. But as you cannot fix the exception, the exception must be passed to the caller so that it too can decide how to re-act to that exception. For example, you may have an open ref cursor or open UTL_FILE handle that needs to be closed when your code terminates. If not, your code will leak resources. So you need to trap exceptions that can occur, clean up, and then re-raise the exception (this is called a resource protection code block in other languages). You may have done a partial transaction - and the exception handler may need to roll back the changes your code made. The bottom line here is that you must re-raise the exception after you have done your "+action stations+" bit. You did not fix the exception. You did not make it more meaningful. In that case you must pass it back to the caller so that it can decide what it needs to do about that exception.
    Using an exception for any other reason - that would likely be the wrong thing to do most of the time.

  • Pls help..Constructor,setter, getter and Exception Handling Problem

    halo, im new in java who learning basic thing and java.awt basic...i face some problem about constructor, setter, and getter.
    1. I created a constructor, setter and getter in a file, and create another test file which would like to get the value from the constructor file.
    The problem is: when i compile the test file, it come out error msg:cannot find symbol.As i know that is because i miss declare something but i dont know what i miss.I post my code here and help me to solve this problem...thanks
    my constructor file...i dont know whether is correct, pls tell me if i miss something...
    public class Employee{
         private int empNum;
         private String empName;
         private double empSalary;
         Employee(){
              empNum=0;
              empName="";
              empSalary=0;
         public int getEmpNum(){
              return empNum;
         public String getName(){
              return empName;
         public double getSalary(){
              return empSalary;
         public void setEmpNum(int e){
              empNum = e;
         public void setName(String n){
              empName = n;
         public void setSalary(double sal){
              empSalary = sal;
    my test file....
    public class TestEmployeeClass{
         public static void main(String args[]){
              Employee e = new Employee();
                   e.setEmpNum(100);
                   e.setName("abc");
                   e.setSalary(1000.00);
                   System.out.println(e.getEmpNum());
                   System.out.println(e.getName());
                   System.out.println(e.getSalary());
    }**the program is work if i combine this 2 files coding inside one file(something like the last part of my coding of problem 2)...but i would like to separate them....*
    2. Another problem is i am writing one simple program which is using java.awt interface....i would like to add a validation for user input (something like show error msg when user input character and negative number) inside public void actionPerformed(ActionEvent e) ...but i dont have any idea to solve this problem.here is my code and pls help me for some suggestion or coding about exception. thank a lots...
    import java.awt.*;
    import java.awt.event.*;
    public class SnailTravel extends Frame implements ActionListener, WindowListener{
       private Frame frame;
       private Label lblDistance, lblSpeed, lblSpeed2, lblTime, lblTime2, lblComment, lblComment2 ;
       private TextField tfDistance;
       private Button btnCalculate, btnClear;
       public void viewInterface(){
          frame = new Frame("Snail Travel");
          lblDistance = new Label("Distance");
          lblSpeed = new Label("Speed");
          lblSpeed2 = new Label("0.0099km/h");
          lblTime = new Label("Time");
          lblTime2 = new Label("");
          lblComment = new Label("Comment");
          lblComment2 = new Label("");
          tfDistance = new TextField(20);
          btnCalculate = new Button("Calculate");
          btnClear = new Button("Clear");
          frame.setLayout(new GridLayout(5,2));
          frame.add(lblDistance);
          frame.add(tfDistance);
          frame.add(lblSpeed);
          frame.add(lblSpeed2);
          frame.add(lblTime);
          frame.add(lblTime2);
          frame.add(lblComment);
          frame.add(lblComment2);
          frame.add(btnCalculate);
          frame.add(btnClear);
          btnCalculate.addActionListener(this);
          btnClear.addActionListener(this);
          frame.addWindowListener(this);
          frame.setSize(100,100);
          frame.setVisible(true);
          frame.pack();     
        public static void main(String [] args) {
            SnailTravel st = new SnailTravel();
            st.viewInterface();
        public void actionPerformed(ActionEvent e) {
           if (e.getSource() == btnCalculate){
              SnailData sd = new SnailData();
           double distance = Double.parseDouble(tfDistance.getText());
           sd.setDistance(distance);
                  sd.setSpeed(0.0099);
              sd.setTime(distance/sd.getSpeed());
              String answer = Double.toString(sd.getTime());
              lblTime2.setText(answer);
              lblComment2.setText("But No Exception!!!");
           else
           if(e.getSource() == btnClear){
              tfDistance.setText("");
              lblTime2.setText("");
       public void windowClosing(WindowEvent e){
                   System.exit(1);
        public void windowClosed (WindowEvent e) { };
        public void windowDeiconified (WindowEvent e) { };
        public void windowIconified (WindowEvent e) { };
        public void windowActivated (WindowEvent e) { };
        public void windowDeactivated (WindowEvent e) { };
        public void windowOpened(WindowEvent e) { };
    class SnailData{
       private double distance;
       private double speed;
       private double time;
       public SnailData(){
          distance = 0;
          speed = 0;
          time = 0;
       public double getDistance(){
          return distance;
       public double getSpeed(){
          return speed;
       public double getTime(){
          return time;
       public void setDistance(double d){
          distance = d;
       public void setSpeed(double s){
          speed = s;
       public void setTime(double t){
          time = t;
    }Pls and thanks again for helps....

    What i actually want to do is SnailTravel, but i facing some problems, which is the
    - Constructor,setter, getter, and
    - Exception Handling.
    So i create another simple contructor files which name Employee and TestEmployeeClass, to try find out the problem but i failed, it come out error msg "cannot find symbol".
    What i want to say that is if i cut below code (SnailTravel) to its own file(SnailData), SnailTravel come out error msg "cannot find symbol".So i force to put them in a same file(SnailTravel) to run properly.
    I need help to separate them. (I think i miss some syntax but i dont know what)
    And can somebody help me about Exception handling too pls.
    class SnailData{
       private double distance;
       private double speed;
       private double time;
       public SnailData(){
          distance = 0;
          speed = 0;
          time = 0;
       public double getDistance(){
          return distance;
       public double getSpeed(){
          return speed;
       public double getTime(){
          return time;
       public void setDistance(double d){
          distance = d;
       public void setSpeed(double s){
          speed = s;
       public void setTime(double t){
          time = t;

  • 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

  • Need plsql exception handler

    Could some good soul share a tested plsql exception handler package that I could use as a start for my project.
    Thanks in anticipation.

    I was actually looking for some already coded package I could use.Nope, there isn't any. Simply because every application differs.
    That's why exceptions were invented in the first place.
    All you need to do is to understand your transactions, what you're doing, and only catch errors you expect.
    Catching anything else is a bug you've created by yourself.
    Don't try to handle anything you didn't expect.

  • 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;

  • Understanding on Exception handling???

    Hi all
    I am doing some bug correction on exception and encounter some problem and questions. Hope someone can help clear my doubts pls. Thanks.
    Q1. I have an exception handling in method A whereby it throw an exception of type ERROR class. I try to catch this ERROR in method B with MyException class which extends from EXCEPTION class. I realise this cannot be done. When I change MyException class to Throwable class, I can catch ERROR thrown. Is it correct that I can only catch exception using superclass? Coz in this case MyException is not a superclass of ERROR class?
    public class MyClass() throws MyException
    void method B()
    try{
    method A();
    }catch(MyException e){
    system.println.out();
    void method A()
    try{
    }catch(IndexOutOfBoundsException e){
    throw new Error("string text');
    Q2. Is it true that I cannot put methodA in MyClass because it throws ERROR class but MyClass throws only MyException?

    Uh.. I think what you just said is called a
    bug, which need to be caught.No ... bugs can cause exceptions, but there are several occasions when a exception can occur that have nothing to do with bugs.
    If for example the hard disk is full when you want to save your file that can hardly be called a bug, but rather an unlucky occurance: an exception to the rule that normally there is enough space left on the drive.
    Also: if somewhere a router shuts down, because it was hit by a lightning an consequently your connection is interrupted then that's not a bug (at least not in your program), but an exception that you must handle.
    But as I said: bugs can cause exceptions: If you allocate a buffer of 1024 bytes and try to write to its 1025th byte then an ArrayIndexOutOfBoundsException is thrown. In this case you generally don't want to catch the exception, but rather prevent it from beeing thrown.

  • Exception Handling in RH_RELATION_MAINTAIN

    can we use Try...Catch Blocks for Exception Handling in RH_RELATION_MAINTAIN.....coz i need to Track the Status message
    coz most of the times it doesn't CATCH and Exception........and i need to send the status msg via Proxy n PI to the JAVA based system............
    So i need to Catch the Exception ................Pls assist................:)
    FORM create_a008 USING l_pernr l_plans l_begda
                     CHANGING l_success.
      CALL FUNCTION 'RH_RELATION_MAINTAIN'
        EXPORTING
          act_fcode           = 'INSE'
          act_plvar           = '01'
          act_otype           = 'S'
          act_objid           = l_plans
          act_istat           = '1'
          act_rsign           = 'A'
          act_relat           = '008'
          act_sclas           = 'P'
          act_sobid           = l_pernr
          act_begda           = l_begda
          act_endda           = '99991231'
        EXCEPTIONS
          maintainance_failed = 1
          OTHERS              = 2.
      IF sy-subrc EQ 0.
        l_success = 'X'.
      ELSE.
        CLEAR : l_success.
      ENDIF.
    ENDFORM.

    sdf

  • 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

  • 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.

  • Exception Handling Confusion!

    I require the following very basic functionality from a function.
    Create or Replace function fnc_get_col3 (a in number, b in number)
    return number
    as
    begin
    return select col3 from TAB1 where col1 = a and col2 = b;
    end fnc_get_util;
    My question is that can I use the regular exception handling (like 'No data found' and 'Too many rows') in above function when i am using the return and select statement in same line
    OR do i have to recreate this function as
    Create or Replace function fnc_get_col3 (a in number, b in number)
    return number
    as
    abc number(5);
    begin
    select col3 into abc from TAB1 where col1 = a and col2 = b;
    return abc;
    exception
    when no data found then
    dbms_ouput.put_line 'No data found'
    end fnc_get_util;
    Thanks in Advance

    Why do you believe it is syntactically valid to return a value this way? The first function does not compile and cannot compile so there is no exception handling to discuss
    SQL> create or replace function f1
      2    return number
      3  is
      4  begin
      5    return select count(*) from emp;
      6  end;
      7  /
    Warning: Function created with compilation errors.
    SQL> sho err
    Errors for FUNCTION F1:
    LINE/COL ERROR
    5/10     PLS-00103: Encountered the symbol "SELECT" when expecting one of
             the following:
             ( - + ; case mod new not null <an identifier>
             <a double-quoted delimited-identifier> <a bind variable>
             continue avg count current exists max min prior sql stddev
             sum variance execute forall merge time timestamp interval
             date <a string literal with character set specification>
             <a number> <a single-quoted SQL string> pipe
             <an alternatively-quoted string literal with character set
             specification>
             <an alternYou would need your SELECT statement to select data into a local variable and to return that local variable as you are doing in your second implementation. It would not make sense, however, to have an exception handler that simply uses DBMS_OUTPUT to display a message-- you should only catch an exception if you can do something meaningful with it.
    Justin

  • 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 ==--

Maybe you are looking for