Exception Handling-rite way??

Hi Friends,
This Exception handling is really causing some problems for me.I run a query,return the resultset,cook the data from my other java class and display it thru my jsp and the last statement from my jsp is to call the close method(commented out).The problem is if some unknown Exception arises the close() method is not being called,causing open connections which later on are
creating some disasters.I tried to implement it now using the finally method,so that it always gets closed,but hte problem is when i call the ReturnResultSet() method and try to cook the data,it says "ResultSet Closed".Please tell me which is the right way to implement this:
public ResultSet ReturnResultSet(String Query) throws Exception
     try{  
       if (datasource != null) {
         connection = datasource.getConnection();
         if (connection != null) {
           statement = connection.createStatement( );
           resultset = statement.executeQuery(Query);         
       return resultset;
     } catch (SQLException sqle)
       sqle.printStackTrace();
       return null;
     finally {       
     try {
       if (resultset != null) resultset.close();
       if (statement != null) statement.close();
       if (connection != null) connection.close();
     catch (SQLException sqle) {
       sqle.printStackTrace();
public void close()
   try { resultset.close(); } catch (Exception ex) {}
   try { statement.close(); } catch (Exception ex) {}
   try { connection.close(); } catch (Exception ex) {}
*/Any help would be appreciated and some duke dollars would be awarded too.Thanks

Ok I think i got your point and i should award you
the duke dollars too,but one last thing to ask.I call
the close() method after all my processing is over,I
just
wanna know should I have the connection.close() thing
inside it,becuase dont that contradicts the whole
connection pool thing,as i am closing a connection
and it has to open a new connection for every
request.Or should i just have resultset.close() and
statement.close() in it.
Thanks for all your helpAre you talking about a standard J2EE container-provided connection pool? If so, then yes, you still need to 'close' the connection. That doesn't actually close it, it just tells the pool it is available to be used again the next time someone asks it for a connection. Hopefully you're not writing your own home-grown "connection pool".

Similar Messages

  • What is the best way of Exception Handling

    There are many ways to handle the exceptions of a program.
    1: You could put every exception handler in the most upper abstract classes.
    2: You could write a generic exception that handles a lot of things.
    3: You could write exceptions handling for every class.
    4: you could group the exception handling.
    many, many more ways.
    Question:
    What is the best way to do this?

    There are many ways to handle the exceptions of a program.
    1: You could put every exception handler in the most upper abstract classes.I woldn't do that always, a class may throw an exception if it's not able to handle it prperly, but it may, so it'll catch it. Throw Exception in abract supper clases only when you are sure the children must always throw the exception, not processing it.
    2: You could write a generic exception that handles a lot of things.Bad idea, if you always throw an Exception no informtaion is provaided about whta happened, if you throw a NullPointerException and a NumberFormatException in one of your method I (for example) colud handle properly both problems, one likely to be a programming erros, so check my cod eagain, and the other like to be an user error in introduciong some data, so I wold ask him for the data again.
    3: You could write exceptions handling for every class.Write exceptions handling for every class that needs it, throwing the exception if at that moment you don't know what to do with it and catching it if yes. Do not employ too many exception handling: execution of try catch blcks is slower than usuall code.
    4: you could group the exception handling.I don't undestand this. What do youmean?
    Question:
    What is the best way to do this? In general thrwo an exception if the class dosen't know what to do with it, the class which uses yours will handle it. If your class can process the Exception, don't be too lazy and process it.
    Employ exceptions always you need them but do not abuse; thay made the code execute slower because the VM machine must check if the exceotions occur.
    abraham.

  • PL/SQL 101 : Exception Handling

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

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

  • Exception Handling Problem In BPM

    All
    I am facing an exception handling problem I am using BPM and , I have caught exception in the transformation step but when there is any data problem in that mapping(mentioned in the transformation)
    it is not throwing the exception . is there any option to collect these type of system exception in  the bpm and give a alert thru mail
    is there any way to collect these type of exception happened in the BPE and raise alert thru generic alert
    Thanks
    Jayaraman

    Hi Jayaraman,
        When you say there is any data problem, does that fail the message mapping that you have defined?
    If the message mapping used in the tranformation fails, it should raise an exception in the BPM.
    Did you test the message mapping using the payload and see if it really fails or not?
    Regards,
    Ravi Kanth Talagana

  • Exception handling

    Quick question, gurus.... From exception handling perspective, is "no_data_found" inclusive of "others". In other words, if my query returns no data and I use "others" without a "no_data_found" will the exception utilize "others"?
    Thanks.
    I give points.
    I supposed I could have tested this using a quick anon block but didn't think about it just now.
    Edited by: sreese on Apr 13, 2012 3:54 PM

    sreese wrote:
    Quick question, gurus.... From exception handling perspective, is "no_data_found" inclusive of "others". In other words, if my query returns no data and I use "others" without a "no_data_found" will the exception utilize "others"?Try it out and let us know, keeping in mind that if your code expects to encounter NO_DATA_FOUND then you need to trap that exception and handle it appropriately. How can you possibly pretend to know how to handle an error that is by it's very definition "unknown" (when others).
    sreese wrote:
    I give points.
    I supposed I could have tested this using a quick anon block but didn't think about it just now.I'd prefer you keep the points and try this out yourself ... much better way to learn.

  • Exception handling framework?

    Can anyone recommend an exception handling framework or perhaps pattern for Applets?
    Thanks, Tom.

    Methinks you're gonna be stuck. Unless every catch block already happens to call some central method (or small set of methods) and passes in the exception, there is no way I can think of to "flip a switch" and magically have all your catch blocks start logging messages when they weren't before. You'll probably have to change the code every place you want to log something. This is why it's a great idea to think of those sorts of things before coding a huge application. :-) I'm not criticizing you since it sounds like you inherited this.

  • Exception Handling and Stack Traces in JDK 1.1.8

    Hi,
    I'm presently maintain and upgrading a Web-Objects 4.5 application that uses the JDK 1.18. There are two constantly recurring exceptions that keep getting thrown, exceptions for which there are no stack traces. These are exceptions thrown by methods that do not presently have throws or try/catch code associated with them.
    My questions are:
    1) Why are there no stack traces available? Is it because the exception handling code is not there, or could there be another reason?
    2) Will the inclusion of exception-handling code ALWAYS lead to stack traces and messages becoming available (if I put a e.printStackTrace() in my catch(Excetion e) clause), or will there be situations where it will not be available?
    3) What is the best way for me to handle these types of exceptions in order to gain the most information possible about their root causes and possible solutions?
    Thanks for your help.

    I have never seen a case where there was no stack trace.
    I have seen cases where the stack trace does not provide line numbers. I have also seen cases where it is less than useful as it terminates on a native call (which is to be expected.)
    However, if you don't call printStackTrace() then you don't get it. And if you catch an exception an throw a different one you also loose information. So you might want to check those possibilities.

  • Error/Exception handling in MQSeries

    Hi,
    What is the robust (yet simple) way to handle any exception generated while doing any operation in MQ Series for e.g. putting messages on queue.
    Currently i have just done exception handling using try/catch blocks in my java application.
    Kindly explain.
    Thanks,
    Sahil

    This forum is specific to the Sun Java System Message Queue
    product and is not a forum on IBM's MQSeries product.
    If you have a question on MQSeries, you may want to look for a forum on IBM's site.

  • Exception handling for mis-addressed messages

    We are using ebXML messaging in WLI. In many of our workflows we start new conversations with trading partners based on the contents of address fields in the messages. Now and again during development a message comes in which is addressed to a TP who doesn't exist. The message fails to be sent and rolls back repeatedly. Is there a simple way to remove these messages from the WLI hub? Can exception handling be used to move messages which are failing to enter the workflows to a special queue automatically?
    thanks
    Ben

    Hi Holger,
    I will not translate the coding into VB. So if you want to do this it is OK with me.
    An idea would be after some testing by the community to provide the functionality as a DLL. This way it could also easily be added to a VB project.
    However I assume that some developers prefer to integrate the coding themselves so that they might add additional customer specific functionlity.
    For example not to raise an exception if a specific error is in the return parameter because they want to ignore it.
    Best regards,
    Andre

  • Exception handling for Scanner console input

    I'm trying to add exception handling to a Scanner console to deal with exceptions caused by non-numeric input. My idea was to do use a try/catch in a for loop and break if no exception occurs.
    Whats happening is the "iNumber = console.nextInt(); " does nothing on subsequent retries, when an exception occurs. That is, I enter "123w", an InputMismatchException occurs, goes into the first catch block, hits "continue" and goes back into the for loop, hits the "iNumber = console.nextInt(); ", then immediately blows through it without executing. Thus, I hit my max loop count and exit with iNumber = 0.
    I'm thinking I may need to instantiate "static Scanner console = new Scanner(System.in);" again in the event of an exception?
    Thanks for any feedback. I'm brand new at Java and learning as fast as I can :)
    Here is the code:
    class ConsoleInput
         public ConsoleInput() // constructor
         static Scanner console = new Scanner(System.in);
         public int GetInput()
              int iNumber = 0;
              for(int i=0; i<3; i++)
              try
                   System.out.print("Please enter a number: ");
                   iNumber = console.nextInt(); // get console input
                   break;
              catch(java.util.InputMismatchException ex)
                   continue;
              catch(Exception ex)
                   continue;
         return iNumber;
    }

    public class Scratch {
      public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        boolean gotAValidInt = false;
        int theInt;
        System.out.println("Enter an int");
        do {
          try {
            theInt = sc.nextInt();
            gotAValidInt = true;
          catch (InputMismatchException exc) {
            System.out.println("Not an int. Try again.");
            sc.next(); // consume the non-int that nextInt couldn't consume
        } while (!gotAValidInt);
    }There are different ways you could structure your loop, but the key is that when nextInt throws an exception, you have to call next() in the catch block to consume the token that nextInt couldn't.
    Edited by: jverd on May 2, 2008 1:52 PM

  • Exception handling in ucm

    hi,
    I have created a custom component that has a service which invokes my custom java methods. I would like to redirect to two error pages depending on the exception thrown by the java method? How exception handling is done in UCM. I see a text box called error messages while creating the service and service actions. But that message is not printed when my java method throws application specific exceptions.
    Is there a way to handle the exception at Service configuraration / UI side and redirect to two different meaningful error pages dependinf upon the thye of exception
    Thanks,
    Siva

    Hi Jayakrishna,
    In General , there are non execptions in BAPIs, because of the reason, that the exception raised in a SAP envoronment may not mean anything for a non SAP initiator. All the exception situations would only fill the return table(TYpe BAPIRET2 or something like that). If you read that table after the call to the bapi, you can understand what has gone wrong.
    Regards,
    Ravi

  • Exception handling in App. package PeopleCode

    Hi,
    I am accessing a table that is on remote database using DBLink for an update/insert operation using SQLExec. I am trying to implement exception handling to account for the scenario where the remote database is offline so that transaction can continue. However when I use the try-catch block in the app. package PeopleCode somehow the processing does not seem to move forward from the error. The App. pacakage code is triggered by the handler of the service operation. The goal is to simply skip the SQLExec if the table is not available. I am not sure if there is any limitation to the fatal SQL errors which the try-catch can handle.
    As expected i get below error when running select on a view which has remote table in the SQL developer as remote database is down.
    ORA-12514: TNS:listener does not currently know of service requested in connect descriptor
    Has anyone enconutered similar issue with exception handling and best way to move forward in this scenario.
    Any response is much appreciated.
    Thanks,
    Gireesh

    I did this with PL/SQL once. Basically, you want to know if the remote database is available before you execute SQL against it. Here is my function. You can then SQLExec something like select 'x' from dual where my_package.link_available('the_link_name') = 1. If you get a result, then the db link is active. If you don't, it is not active.
    FUNCTION LINK_AVAILABLE(pv_name VARCHAR2)
      RETURN NUMBER AS
            lv_result PLS_INTEGER;
            lv_name   VARCHAR2(128);
        BEGIN
            lv_name := UPPER(pv_name);
            -- parameter check to avoid SQL injection with dynamic SQL below
            -- if the following selects no rows, it will fall through to exception
            -- and return 0;
            SELECT 1
              INTO lv_result
              FROM ALL_DB_LINKS
             WHERE DB_LINK = lv_name;
            -- if we made it this far, then the parameter was a valid db link name
            -- execute SQL to test
            EXECUTE IMMEDIATE 'SELECT 1 FROM PS_INSTALLATION@' || lv_name INTO lv_result;
            RETURN lv_result;
        EXCEPTION
            WHEN OTHERS THEN
                RETURN 0;
      END LINK_AVAILABLE;

  • Exception Handling in ADF

    Jdeveloper version 11.1.1.5.0
    Use Case :
    My application has :- 1 Jspx page ( testPage.jspx ) , 1 taskflow ( testExceptionFlow.xml ) , 1 pageFragment ( testOperation.jsff ).
    I have employee table dragged as table on testOperation.jsff with 4 buttons :
    1. Delete - Executes the VO's Delete action.
    2. Commit - AM's commit operation ( through datacontrol )
    3. CustomDeleteAndCommit - One method in VOImpl which deletes the currentRow and calls this.getDBTransaction().commit() method.
    4. CustomCommitThroughBean - Action listener in beans calls the commit through operation binding.
    I have secured my application and create two users in jazn.xml User1 and User2. Now both users are logged in to the application using different browser.
    Both users can see employee with empId 100.
    User1 selects a employee with empId 100 and clicks Delete button. Further clicks Commit button.
    User2 selects the same employee with empId 100 and clicks Delete button. Further he can choose to commit through different options :
    a) Commit
    b) CustomCommitThroughBean
    OR
    CustomDeleteAndCommit
    Obviously there will be jboException stating that row is already delete. When I am calling it through CustomCommitThroughBean operationBinding.getErrors() has errors, so I don't see error on UI.
    I see a couple of posts about different ways of handling Exception :
    [Using Exception Handler in an ADF Task Flow | https://blogs.oracle.com/ADFProgrammers/entry/using_exception_handler_in_an]
    [Extending the ADF Controller exception handler | https://blogs.oracle.com/jdevotnharvest/entry/extending_the_adf_controller_exception_handler]
    [Task Flow Exception Handler | http://adfpractice-fedor.blogspot.com/2011/12/task-flow-exception-handler-you-must.html]
    [Exception Handling in adf (Part 1) | http://adfwithejb.blogspot.com/2012/05/exception-handling-in-adf-part-1.html ]
    Which method of exception handling is applicable should be chosen ?
    I just want to notify user about exception through some custom message and table should get refreshed for further operation.
    My observations :
    I get an error dialog in case :
    Commit & CustomDeleteAndCommit
    whereas no default error in case : CustomCommitThroughBean
    I have uploaded my application [here | http://dl.dropbox.com/u/70986236/BlogApplication/OperationBindingExecuteErrorApp.zip ] . Want to implement exception handling in this application.
    Thanks,
    Rajdeep
    Edited by: Rajdeep on Jul 26, 2012 9:45 PM

    When you invoke an operation programmatically through an ADF OperationBinding, the eventual exception is not thrown to you but it is reported to the BindingContainer and the BindingContainer automatically adds a FacesMessage of ERROR severity to the FacesContext. If you have an <af:messages> tag in your ADF Faces page, this error message should be displayed automatically.
    Dimitar

  • Exception handling in report

    Hello all,
    i want oto implement exception handling in report.
    scenario:
    i have a parameter form par.fmb
    i provide parameter on form then call the report.
    if there is some error generate while query of report then how to handle it, so that user get the message.
    below query is used in report:
    SELECT SPC_ITEM_CODE,GENERATE_ITEM_NAME(SPC_ITEM_CODE),MOD_DATE,OBU,REQ_NO,REQ_QTY,OQC_QTY,SPC_ITEM_QTY,process
    , INSP_LOT_SIZE,REMARKS,INSP_STATUS
    FROM OQC_DATA
    WHERE (REQ_NO=:REQ_NO OR :REQ_NO IS NULL) AND trunc(MOD_DATE) BETWEEN :FROM_DATE AND :TO_DATE
    AND SPC_LOCN_CODE=:LOCN_CODE
    ORDER BY REQ_NO,SPC_ITEM_CODE
    here: GENERATE_ITEM_NAME(SPC_ITEM_CODE) is database function.
    as spc_item_code is column in OQC_DATA table, it any how there is null value in spc_item_code then error will raise, i and want to handle this error sothat ,
    i found the reason.
    Thanks
    yash
    Edited by: yash_08031983 on Jan 27, 2012 9:11 PM

    yash_08031983 wrote:
    Hello all,
    i want oto implement exception handling in report.
    scenario:
    i have a parameter form par.fmb
    i provide parameter on form then call the report.
    if there is some error generate while query of report then how to handle it, so that user get the message.
    below query is used in report:
    SELECT SPC_ITEM_CODE,GENERATE_ITEM_NAME(SPC_ITEM_CODE),MOD_DATE,OBU,REQ_NO,REQ_QTY,OQC_QTY,SPC_ITEM_QTY,process
    , INSP_LOT_SIZE,REMARKS,INSP_STATUS
    FROM OQC_DATA
    WHERE (REQ_NO=:REQ_NO OR :REQ_NO IS NULL) AND trunc(MOD_DATE) BETWEEN :FROM_DATE AND :TO_DATE
    AND SPC_LOCN_CODE=:LOCN_CODE
    ORDER BY REQ_NO,SPC_ITEM_CODE
    here: GENERATE_ITEM_NAME(SPC_ITEM_CODE) is database function.
    as spc_item_code is column in OQC_DATA table, it any how there is null value in spc_item_code then error will raise, i and want to handle this error sothat ,
    i found the reason.You can handle the error in two way.
    First from the function, you can use exception in it and through 0(zero) if it didn't get any value.
    2nd use nvl function in the sql like nvl(GENERATE_ITEM_NAME(SPC_ITEM_CODE),0) if number data type or NVL(GENERATE_ITEM_NAME(SPC_ITEM_CODE),'n/a') if char data type output.
    You can also use decode.
    Hope this will help you.

  • Exception handling in jinitiator

    hallo,
    we are currently using jinitiator 1.3.1.9 and i have a little question concerning the exception handling in it. i don't think, that the handling differes to older version, so maybe one can help me out though he uses an "older" version.
    now the problem. we use java functionality either in webmode (jinitiator) and in client-server-mode (wrapper pl/sql unit) and want to pass the java exception trace to the forms, so that we can handle errors in user interaction. we found a way to da that by developing a printstream, which collects trace information in a string. this method works well in client-server-mode but not in webmode. in the first case all the normal trace information is written with the printstream-method println(String). in the webmode case, a different method is used, println(char[]). the strange thing about it is, that the character array contains address information for an object (maybe the string). i my opinion the behaviour is because of the jinitiator. does anyone know about the exception handling and collecting the trace information in jinitiator?? thanks very much in advance.
    regards
    steffen silberbach

    hi again,
    thanks for answering, but I think you got me wrong or I didn't make myself clearly. I don't want to pass a PL/SQL error to the bean to have it printed out on the console. I want it the other wa around. my problem was to get the stack trace of a java exception and make it accessible to the form to print it out as a message for instance. unfortunately this way is quite impossible to do, because jinitiator has a different exception handling to the sun VM. the jinitiator implements the printStackTrace(*) methods as native calls and obviously the underlying code handles the addresses of the passed trace objects and prints them out the a special console somehow. so if one overwrites the printStack() methods in his own Exception, he gets a problem because of the different exception trace handling in jinitiator.

Maybe you are looking for

  • Metadata Loads (.app) - What is best practice?

    Dear All, Our metadata scan and load duration is approximately 20 mins (full load using replace option). Business hfmadmin has suggested the option of partial dimension loads in an effort to speed up the loading process. HFM System Admins prefer Meta

  • Mountain lion finder rearranges my icon files

    I've discovered a bug: Mountain Lion's Finder rearranges my icon files by alphabet when I paste more than one document into a directory.  It happened twice.  Sometimes I prefer visual arrangement in directories. SECOND PROBLEM: I also don't like the

  • Ios 6.1.3 is awesome but why it is slow man ?

    moji

  • Re-Org/Update Program for Route determination

    Hi does anyone know if there is a Re-org / Update program for Routes ? I have added new routes, against Shipping conditions from NO and SE to many Western European Countries ,  and would like to update Sales orders/ deliveries with these new routes M

  • Can I go back to my iLife '08 version of iPhoto?

    I have Mac 10.6.8.  My hard drive crashed, but since I had everything backed up using Time Machine, I feared not.  Apple replaced the hard drive.  My husband did not use migration assistant to set up the new hard drive since he reasoned that it was c