FOR Loop Exception Handling

Given the following code:
for x in my_cursor loop
    begin
        <<stmt_1>>
        <<stmt_2>>
    exception
        when others then
            <<log_error>>
    end;
end loop;Say there are 5 x's in my_cursor. On element x3, stmt_1 works fine but stmt_2 throws an exception. I'd like to rollback ONLY the work done on x3 (in this case, stmt_1), then continue the loop from the next element, x4. Can this be achieved with some combination of savepoint/rollback?

As I said, you can put the increment operation at the end of the block when you know no more exceptions could be raised, i.e.
declare
    cnt number;
    ex  exception;
begin
    cnt := 0;
    for x in 1..5 loop
        begin
            savepoint s;
            insert into test_tbl values(1/(3-x));
            cnt := cnt+1;
        exception
            when others then
                rollback to savepoint s;
        end;
    end loop;
    dbms_output.put_line('cnt='||cnt);
end;You could also increment the counter outside of the PL/SQL block, i.e.
declare
    cnt number;
    ex  exception;
    num_success number;
begin
    cnt := 0;
    for x in 1..5 loop
        begin
            num_success := 0;
            savepoint s;
            insert into test_tbl values(1/(3-x));
            num_success := sql%rowcount;
        exception
            when others then
                rollback to savepoint s;
        end;
        cnt := cnt + num_success;
    end loop;
    dbms_output.put_line('cnt='||cnt);
end;And you can refactor your code so that the components to hide some of this complexity, i.e.
SQL> ed
Wrote file afiedt.buf
  1  create or replace procedure try_insert_test_tbl(
  2    p_val in number,
  3    p_num_success out number )
  4  as
  5    divide_by_zero exception;
  6    pragma exception_init( divide_by_zero, -1476 );
  7  begin
  8    savepoint s;
  9    insert into test_tbl values( 1/(3-p_val ) );
10    p_num_success := sql%rowcount;
11  exception
12    when divide_by_zero
13    then
14      p_num_success := 0;
15* end;
SQL> /
Procedure created.
SQL> ed
Wrote file afiedt.buf
  1  declare
  2      cnt number;
  3      ex  exception;
  4      num_success number;
  5  begin
  6      cnt := 0;
  7      for x in 1..5 loop
  8          try_insert_test_tbl( x, num_success );
  9          cnt := cnt + num_success;
10      end loop;
11      dbms_output.put_line('cnt='||cnt);
12* end;
SQL> /
cnt=4
PL/SQL procedure successfully completed.There is no way for DCL statements to affect the state of PL/SQL variables. But you can generally structure your code in such a way that this is unnecessary.
Justin

Similar Messages

  • FOR LOOP EXCEPTION not working !!! please help

    Hi,
    Why is the NO_DATA_FOUND execption not getting executed. ????
    Hereis the code....
    CURSOR newreccur IS
    SELECT * from emp_table;
    BEGIN
    v_file_handle := UTL_FILE.FOPEN('out','new.dat','W');
    BEGIN
    FOR emp_rec IN newreccur LOOP
    -- Write procurement records
    UTL_FILE.PUT(v_file_handle,'emp_rec.num');
    END LOOP;
    EXCEPTION WHEN NO_DATA_FOUND THEN
    dbms_output.put_line ('No data found ')
    END;
    EXCEPTION
    WHEN UTL_FILE.INVALID_PATH
    THEN
    DBMS_OUTPUT.PUT_LINE ( 'Invalid Path ' || TO_CHAR (SQLCODE) );
    UTL_FILE.FCLOSE_ALL;
    END;

    cursor for loops do not raise no_DatA_found - they simply stop looping when they run out of data. you can set a variable within the loop, and then check it after the loop if you need to know if data was returned or not.

  • OPEN out_cur FOR        SELECT  exception handling help

    Here is the stored procedure for reading a data based on the input, if no data then return null ref cursor and proper error message.
    I am not sure, i am handling proper exception handling ? Please help me to complete this item.
    Thanks.
    PROCEDURE testing
    module IN VARCHAR2,
    module_id IN VARCHAR2,
    out_cur OUT SYS_REFCURSOR,
    out_error_no OUT NUMBER
    BEGIN
    out_error_no := 0;
    CASE
    WHEN module = 'a' AND module_id = 'b' THEN
    BEGIN
    OPEN out_cur FOR
    SELECT id,
    mime_type,
    file_length,
    file_name ,
    uploadeddate,
    created_user ,
    status_name
    FROM l_table_cnt
    WHERE id = module_id;
    EXCEPTION
    WHEN OTHERS THEN
    OPEN out_cur_file_cursor FOR
    SELECT
    NULL id,
    NULL mime_type,
    NULL file_length,
    NULL file_name,
    NULL uploadeddate,
    NULL created_user,
    NULL status_name
    FROM dual
    WHERE 1= 0;
    out_error_no := 2;
    RAISE_APPLICATION_ERROR(-20024,'No Document ');
    END;

    Venkadesh wrote:
    The correct way is to just open the ref cursor and pass it back and then the receiving code that is going to use that cursor handles whether there is any code in it or not. can you please explain with simple exampleIs it really that difficult?
    Ok...
    Here's the procedure to return a ref cursor...
    SQL> ed
    Wrote file afiedt.buf
      1  create or replace procedure get_rc(p_deptno in number, p_rc out sys_refcursor) is
      2  begin
      3    open p_rc for 'select * from emp where deptno = :1' using p_deptno;
      4* end;
    SQL> /
    Procedure created.Now we have some application that wants to consume a ref cursor... in this case the application is SQL*Plus, but it could be Java or .NET etc.
    It declares it's local reference to the ref cursor...
    SQL> var r refcursor;then calls the procedure to get a ref cursor reference assigned...
    SQL> exec get_rc(10, :r);
    PL/SQL procedure successfully completed.Now, the application itself determines if there is any data when it comes to actually perform the fetches on it...
    SQL> print r;
         EMPNO ENAME      JOB              MGR HIREDATE                    SAL       COMM     DEPTNO
          7782 CLARK      MANAGER         7839 09-JUN-1981 00:00:00       2450                    10
          7839 KING       PRESIDENT            17-NOV-1981 00:00:00       5000                    10
          7934 MILLER     CLERK           7782 23-JAN-1982 00:00:00       1300                    10in the above case it had data, so it displayed it.
    So what if there isn't any data...
    SQL> exec get_rc(90, :r);
    PL/SQL procedure successfully completed.
    SQL> print r;
    no rows selected
    SQL>SQL*Plus (the application that calls the procedure) is the one that has determined that there was not data when it came to fetch it (using the print statement in this case). And when it found there was no data it handled it itself (in this case printing the message "no rows returned").
    The procedure doesn't have to do any overhead of determining if there is data going to be returned or not, because it's not it's responsibility and completely unnecessary. The calling application can easily determine if there is data or not when it starts to try and fetch it.

  • Best Practice for Implementing Exception Handling in BPEL

    Hi All,
    what is the best practice and the approach to follow Exception Handling in BPEL.
    1) Do we need to implement Exception Handling in BPEL as we do in Java, means
         method 3 throws error to method 2 (if any) and
         method 2 throws error to method 1 (if any) and
         finally method 1 throws error to the main Class.
    If we replicate the above scenario to BPEL
    In BPEL main Scope have Custom Fault, Catch ALL
         Each Invoke is surrounded by a Scope Activity with Remote Fault, Binding Fault & Custom Fault
    and follow the paradigm of Java, assuming we have Inner Scopes
         [ OR ]
    2) In BPEL main Scope have all exceptions defined like
         Remote Fault,
         Binding Fault,
         anyOther System Fault (selectionFailure / forcedTermination),
         Custom Fault (if required) and
         CatchALL
         and also
         each Invoke is surrounded by a Scopes Acitivity with Custom Fault (business fault) exception Handling
    I feel 1st one may not be a good practice, may be i am wrong...
    Any Suggestions from experts.
    Thanks in Advance
    anvv sharma

    Hi-
    In you can create different scope and use catch branch to catch binding, remote, custom faults, business faults etc. If an error happens in a scope it will not move to the next scope( eg: you have 3 scope, error occured in 2nd scope then it will not propogate to the 3rd scope. One thing to be noticed here is your transaction in the 1st scope doesnt gets commited when an error happens in 2d scope).
    You can have a catch all to catch error which are not being caught at catch level. So if any error happens which is not defined in catch block then then it will be caught in catch all branch.
    Edited by: 333333 on Apr 12, 2011 9:39 AM

  • Multiple HTTP Requests in for loop response handling

    i am working on stock market portfolio. a user saves his stock name , buy price ,etc .i've added this details in database.but while viewing his portfolio he should even get the current price of d stocks he has added. while retrieving i fetch all data from database set them in a bean and for each stock i make a HTTP Request. in result handler i event set the current price into the bean. Problem is my entire application is displayed with all the CurrentPrice fields with null.
    private function selectContacts():void
        trace("select before");
        stmt.sqlConnection = this.isDbConnected(conn);
        stmt.text = "SELECT * FROM stocks_t";
        stmt.addEventListener(SQLErrorEvent.ERROR, sqlError);
        stmt.addEventListener(SQLEvent.RESULT, sqlResult);
        stmt.execute();
        trace("select after");
    private function sqlResult(res:SQLEvent):void{
        httpServ = new HTTPService();
        data1 = stmt.getResult().data;
        stockList = new ArrayCollection();   
        for(var d:int=0;d<=data1.length-1;d++)
            myPortfolioBean = new MyProtfolioBean();
            httpServ.url = 'http://quote.yahoo.com/d/quotes.csv?s='+data1[d].stockName+'&f=snl1a';
            httpServ.method = 'GET';
            httpServ.addEventListener(ResultEvent.RESULT,yDataResult);
            httpServ.addEventListener(FaultEvent.FAULT,yDataFault);
            httpServ.showBusyCursor= true;
            httpServ.send();
            myPortfolioBean.stockNameB = data1[d].stockName;
            myPortfolioBean.buyB = data1[d].buy;
            myPortfolioBean.quantityB = data1[d].quantity;
            myPortfolioBean.totalQuantityAmountB = data1[d].totalQuantityAmount;
            myPortfolioBean.profitB = data1[d].profit;
            stockList.addItem(myPortfolioBean);
    public function yDataResult(evt:ResultEvent):void
        var s:String = evt.result as String;
        var a:Array = s.split(",");
        //To add to a form or individual fields
        lastTraded =  a[2].toString();
        lastTradedFloat = parseFloat(lastTraded);
        myPortfolioBean.currentB = lastTradedFloat;
        stockList.addItem(myPortfolioBean);
        //stockList.addItem({current:lastTradedFloat});
    the yDataResult() is called after the entire datagrid is displayed on screen as a result of which the CurrentPrice in datagrid column in null. Eg: user has added google ,yahoo,apple( CurrentPrice  is null for all three values) after some time three more rows (as a result of call to yDataResult) with CurrentPrice xx.xx displayed. I want merged results.

    hello ,
    "CurrentPrice" is "lastTradedFloat" sorry for the ambiguity.
    and u got my problem but there is an issue ..
    all the results are set using "sqlResult" except the "lastTradedFloat" which is set in "ydataResult".
    but i confused with HTTP ResultEvent Execution.
    first "sqlResult" method is called arrayCollection is populated. then result is displayed on screen.( lastTraded value is null then)
    then "ydataResult" executes again manipulating data in arraycollection.
    what i want is data in "sqlResult" and "ydataResult" to be set sequentially then callin my display page . such that display is correct.

  • Good exception handling policy for Java web application

    I'm looking for a good exception handling policy for Java web application. First I found this Java exception handling best practices - How To Do In Java which says that you should never catch the Trowable class nor use e.printStackTrace();
    Then I found this Oracle page The Message-Driven Bean Class - The Java EE 6 Tutorial, which does just that. So now I'm confused. Is there a good page online for an exception handling policy for Java EE Web applications? I have a hard time finding one. I've read that you should not catch the Exception class. I've been catching it previously to make sure that some unknown exception doesn't slip through early in the loop and stops all other customers from executing later on in the loop. We have a loop which runs once a minute implemented using the Quartz framework. Is it OK if you just change the implementation to catch the RuntimeException class instead of the Exception class? We're using Java 7 and the Jetty Servlet Container.

    I'm looking for a good exception handling policy for Java web application.
    If you have not done so I suggest you start by reviewing the several trails in The Java Tutorials.
    Those trails cover both HOW to use exceptions and WHEN to use them.
    This trail discusses  the 'controversy' you mention regarding 'Unchecked Exceptions'
    http://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html
    Unchecked Exceptions — The Controversy
    Because the Java programming language does not require methods to catch or to specify unchecked exceptions (RuntimeException, Error, and their subclasses), programmers may be tempted to write code that throws only unchecked exceptions or to make all their exception subclasses inherit from RuntimeException. Both of these shortcuts allow programmers to write code without bothering with compiler errors and without bothering to specify or to catch any exceptions. Although this may seem convenient to the programmer, it sidesteps the intent of the catch or specify requirement and can cause problems for others using your classes.
    Why did the designers decide to force a method to specify all uncaught checked exceptions that can be thrown within its scope? Any Exception that can be thrown by a method is part of the method's public programming interface. Those who call a method must know about the exceptions that a method can throw so that they can decide what to do about them. These exceptions are as much a part of that method's programming interface as its parameters and return value.
    The next question might be: "If it's so good to document a method's API, including the exceptions it can throw, why not specify runtime exceptions too?" Runtime exceptions represent problems that are the result of a programming problem, and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way. Such problems include arithmetic exceptions, such as dividing by zero; pointer exceptions, such as trying to access an object through a null reference; and indexing exceptions, such as attempting to access an array element through an index that is too large or too small.
    Generally don't catch an exception unless you plan to HANDLE the exception. Logging, by itself is NOT handliing.
    First I found this Java exception handling best practices - How To Do In Java which says that you should never catch the Trowable class nor use e.printStackTrace(); 
    That article, like many, has some good advice and some poor or even bad advice. You get what you pay for!
    I've read that you should not catch the Exception class.
    Ok - but all that does is indicate that a problem of some sort happened somewhere. Not very useful info. Java goes to a lot of trouble to provide specific exceptions for specific problems.
    I've been catching it previously to make sure that some unknown exception doesn't slip through early in the loop and stops all other customers from executing later on in the loop.
    If the exception is 'unknown' then maybe it NEEDS to 'stop all other customers from executing later on in the loop'.
    That is EXACTLY why you don't want to do that. You need to identify which exceptions should NOT stop processing and which ones should.
    Some 'unknown' exceptions can NOT be recovered and indicate a serious problem, perhaps with the JVM itself. You can NOT just blindly keep executing and ignore them without risking data corruption and/or the integrity of the entire system Java is running on.
    Is it OK if you just change the implementation to catch the RuntimeException class instead of the Exception class? We're using Java 7 and the Jetty Servlet Container.
    No - not if you want a well-behaved system.
    Don't catch exceptions unless you HANDLE/resolve them. There are times when it makes sense to log the exception (which does NOT handle it) and then raise it again so that it gets handled properly later. Yes - I know that is contrary to the advice given in that article but, IMHO, that article is wrong about that point.
    If you have ever had to maintain/fix/support someone else's Java code you should already understand how difficult it can be to find WHERE a problem occurs and WHAT the exact problem is when exceptions are not handled properly.

  • ADF Task Flow Exception Handling

    Hi ,
    I tried a very simple thing for taskFlow exception handling.
    I created a bounded task flow with a page fragment (View1.jsff) and another view which is the TaskFlow ExceptionHandler (error.jsff).
    The view1.jsff has a button whose action is bound to the backing bean. In the backingBean method I deliberately do division by 0.
    Since this is an unHandled exception, I would have expected the control to come to error.jsff. But, instead I am shown a pop up box with the error message.
    Why is the control not getting redirected to error.jsff ?
    Thanks.
    S.Srivatsa Sivan

    Hi Frank , im having the same problem.
    I want to handle exceptions that occur while navigating task flows (example: A user navigates to a task flow that he/she does not have view permission)
    I tried using a view activity and method activity as the exception handler but none of them works, the exception is still not handles. It does not even navigate to the exception handler on the task flow.
    on the view page i have:
    <af:panelStretchLayout topHeight="50px" id="psl1">
    <f:facet name="top">
    <af:panelGroupLayout layout="scroll"
    xmlns:af="http://xmlns.oracle.com/adf/faces/rich"
    id="pgl1">
    Error message:  
    <af:outputText value="#{controllerContext.currentRootViewPort.exceptionData.message}" id="ot2"/>
    </af:panelGroupLayout>
    </f:facet>
    <f:facet name="center">
    <af:outputText value="#{my_exception_Handler.stackTrace}" id="ot1"/>
    <!-- id="af_one_column_header_stretched" -->
    </f:facet>
    </af:panelStretchLayout>
    I tried getting the error message and stacktrace from the controllerContext via EL like this "#{controllerContext.currentRootViewPort.exceptionData.message}"
    and from the controllerContext class in functions that i have declared in my_exception_Handler class like this
    " ControllerContext ctx = ControllerContext.getInstance();
    ViewPortContext vCtx = ctx.getCurrentViewPort();
    if(vCtx.getExceptionData() != null){
    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(stringWriter);
    vCtx.getExceptionData().printStackTrace(printWriter);
    return stringWriter.toString();"
    But all this dont even matter because when the exception occurs on the task flow it does not navigate to the default exception handler.
    thanks for your interest and help in advance.
    Cyborg_0912

  • Exception Handling (in Mapping) with out using BPM

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

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

  • It takes long time to invoke the Exception handler code

    In our setup there is firewall between the Appserver that is using toplink and the database.The firewall terminates idle connection on any port if the connection is idle for 1 hr.So i have implemented an exception handler to reconnect when the connection is broken.The code works fine but It takes 15 mins for the exception handler code to be invoked.
    The database is Oracle and the driver is thin driver,OS is solaris.No external connection pool
    I had registered the exceptionhandler to the serversession,should i register it with each ClientSession?

    yes ,15 mins is the time taken before the server session's exception handler code is invoked.
    The following is the exception handler code on the sever session.Any thing wrong?
    server.setExceptionHandler(new ExceptionHandler()
    public Object handleException(RuntimeException ex)
    {//This method is executed only after 15 min ,if the connection is broken
    String mess=ex.getMessage();
    System.out.println("In handler excep mess is "+mess);
    if ((ex instanceof DatabaseException) && (mess.equals("connection reset by peer.")||(mess.indexOf("IOException :Broken pipe")!=-1)))
    DatabaseException dbex = (DatabaseException) ex;
    dbex.getAccessor().reestablishConnection (dbex.getSession());
    return dbex.getSession().executeQuery(dbex.getQuery());
    return null;
    What could be wrong ?
    I tried Oracle's connection cache Impl created a connection pool using the same thin driver and on the same env.SQLException is thrown immediately on using the broken connection.so I feel the driver is not causing any problem.
    Is there any way in toplink to keep the connections active?or Is there any way to poll all connections in the connection pool and check If they are connected instead of waiting until the exception gets thrown and handle it?

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

  • Struts exception handling - Exception handler

    Hi ,
    I need some help for struts exception handling . Global exception is working fine in my struts application . But I need to show the exception stack trace also in the screen whenever the exception occurs.I guess this can be achieved if we use a custom exception handler instead of struts default exception handler . Can anyone please provide me a sample code to deal with a custom ExceptionHandler class ?
    Thanks in advance...
    Regards,
    BG

    The struts provides org.apache.struts.action.ExceptionHandler class for creating the custom exception handlers. All the custom Exception Handlers should extend the ExceptionHandler class and override the execute() method.
    //An Example
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;
    import org.apache.struts.action.ExceptionHandler;
    import org.apache.struts.config.ExceptionConfig;
    public class CustomExceptionHandler extends ExceptionHandler {
    public ActionForward execute(Exception exception, ExceptionConfig config, ActionMapping mapping, ActionForm formInstance,
    HttpServletRequest request, HttpServletResponse response) throws ServletException {
    try {
    // TODO CustomeCode
    System.out.println("Exception Handler for the specific error");
    }catch (Exception e) {
    return (super.execute(exception, config, mapping, formInstance, request, response));
    Struts-config.xml File
    <exception key="error.system" type="java.lang.RuntimeException"
    handler="com.visualbuilder.handler.CustomExceptionHandler" path="/index.jsp" />
    Note:- This will transfer the control to the index.jsp after calling the exception handler. In the struts-config.xml we are adding the global exception for RuntimeException. You can add any exception like the previous example to some actions only.
    I have taken this example from following link. You may visit it.
    http://www.visualbuilder.com/jsp/struts/tutorial/pageorder/38/
    I would like if you share knowledge with me.

  • Exception Handling best practices?

    Hi, Where can I find the tutorial on exception handling best practices on oracle website?
    I am looking for the sun standards for the exception handling.

    By the way, the google keywords to find that tutorial are "java exception tutorial". In general to find a Java tutorial on topic X the google keywords are "java X tutorial". Prefer tutorials from Oracle when scanning the list of links you get back.

  • Simple exception handling

    Hello,
    I am trying to figure out how to add exception handling to a procedure so that I can save the error message into a table. Here is the simple procedure that calls another procedure, and the error is always due to some problem in the subprocedure, which will continue to occur periodically:
    (var1 integer, var2 integer)
    is
    begin
    subprocedure (var1, var2);
    commit;
    end;
    Here is my guess for adding exception handling:
    (var1 integer, var2 integer)
    is
    begin
    subprocedure (var1, var2);
    exception
    insert into errortable (col1) values (error_message);
    commit;
    end;
    I currently have the java setup with error handling using the try-catch system which displays the oracle error message in the tomcat window.
    How do I setup the oracle procedure to send my user-defined error message to the tomcat window?
    Any suggestions are greatly appreciated. TIA.

    raise_application_error will automatically end the transaction by calling ROLLBACK.
    So you may have to COMMIT before calling raise_application_error to perserve your insert.
    But i see you are writing into errorlog. The best way to do it is have a seperate procedure, define it as a autonomous transation and call it in your exception block. Something like this
    create or replace procedure log_error(pErrorMessage varchar2, pDate date)
    as
      pragma autonomous_transaction;
    begin
      insert into errorlog values (pErrorMessage, pDate);
      commit;
    end;
    /in your exception block do this.
    EXCEPTION
    WHEN OTHERS THEN
    log_error(dbms_utility.format_error_stack,SYSDATE)---Insert Into your Table--
    raise_application_error(-20101, dbms_utility.format_error_stack); ---Raise application error back to Java App---

  • Provider Hosted App - Exception Handling and Logging

    Hello,
    I would like to use file system to log the exceptions (The IIS server in which the APP is configured) for Provider Hosted App - Could anyone share some blogs/links related to that?
    Thanks in advance,

    Well the first time, I asked the question, I think I
    was not so clear. Please let me explain this in
    detail. I am not architect, so correct me if I am
    wrong.
    I want to use log4J but definitely want to avoid using
    them directly in our package, idea is to create
    wrappers around all the external API, jar we are
    using. At logging side I feel little comfortable.
    But having little difficulty in thinking and designing
    about Exception handling framework.
    1. My aim is to create a general framework in 3 broad
    categories (For Presentation tier, For Business tier,
    for Data Access tier)
    2. For each tier if you import those already created
    framework classes, all developers should be just able
    to use the methods of exception framework and use them
    in catch block and throw them.
    Example:- I would like to create a class called
    MyProjectExceptionDecider, which will decide the type
    of exception in Business Tier and then use my
    MyProjectExceptionErrorParser, which reads the XML
    document and gets a related message number and error
    message.
    This MyProjectExceptionErrorParser then passes the
    right exception to MyProjectExceptionDisplayer which
    will display the exception with right message and
    message number.
    And something more like this. I am not yet getting
    complete picture.
    3. So, if you have done something similar and if you
    have the class diagram and sequence diagram for such
    exception handling, I would be grateful if you are
    willing to share with me.
    Please let me know, if you have different ideas. I
    request you all to participate and throw your ideas
    and suggestions.
    Srikanthgenerally, wheather or not you are using log4j or anything else, when designing exception handling mechnism, you need to decide on where or by whom an exception will be handled, and if the exception needs to be displyed, and how it is displayed.

  • Exception handling for all the insert statements in the proc

    CREATE PROCEDURE TEST (
    @IncrStartDate DATE
    ,@IncrEndDate DATE
    ,@SourceRowCount INT OUTPUT
    ,@TargetRowCount INT OUTPUT
    ,@ErrorNumber INT OUTPUT
    ,@ErrorMessage VARCHAR(4000) OUTPUT
    ,@InsertCase INT --INSERT CASE INPUT
    WITH
    EXEC AS CALLER AS
    BEGIN --Main Begin
    SET NOCOUNT ON
    BEGIN TRY
    DECLARE @SuccessNumber INT = 0
    ,@SuccessMessage VARCHAR(100) = 'SUCCESS'
    ,@BenchMarkLoadFlag CHAR(1)
    ,@BenchmarkFlow INT
    ,@MonthYearStart DATE
    ,@MonthYearEnd DATE
    ,@StartDate DATE
    ,@EndDate DATE
    /* Setting the default values of output parameters to 0.*/
    SET @SourceRowCount = 0
    SET @TargetRowCount = 0
    /*Setting the Start and end date for looping */
    SET @MonthYearStart = @IncrStartDate;
    SET @MonthYearEnd = @IncrEndDate;
    /* Setting the @InsertCase will ensure case wise insertion as this sp will load data in different tables
    @InsertCase =0 means data will be inserted in the target TAB1
    @InsertCase =1 means data will be inserted in the target TAB2
    @InsertCase =2 means data will be inserted in the target TAB3
    @InsertCase =3 means data will be inserted in the target TAB4
    @InsertCase =4 means data will be inserted in the target TAB5
    @InsertCase =5 means data will be inserted in the target TAB6
    if @InsertCase =0
    WHILE (@MonthYearStart <= @MonthYearEnd)
    BEGIN
    SET @StartDate = @MonthYearStart;
    SET @EndDate = @MonthYearEnd;
    /* Delete from target where date range given from input parameter*/
    DELETE FROM TAB1
    WHERE [MONTH] BETWEEN MONTH(@StartDate) AND MONTH(@EndDate)
    AND [YEAR] BETWEEN year(@StartDate) and year(@EndDate)
    /*Insert data in target-TAB1 */
    BEGIN TRANSACTION
    INSERT INTO TAB1
    A,B,C
    SELECT
    A,BC
    FROM XYZ
    COMMIT TRANSACTION
    SET @MonthYearStart = DATEADD(MONTH, 1, @MonthYearStart)
    SELECT @TargetRowCount = @TargetRowCount + @@ROWCOUNT;
    END -- End of whileloop
    END TRY
    BEGIN CATCH
    IF @@TRANCOUNT>0
    ROLLBACK TRANSACTION
    SELECT @ErrorNumber = ERROR_NUMBER() ,@ErrorMessage = ERROR_MESSAGE();
    END CATCH
    END--End of Main Begin
    I have the above proc inserting data based on parameters  where in @InsertCase  is used for case wise execution.
     I have written the whole proc with exception handling using try catch block.
    I have just added one insert statement here for 1 case  now I need to add further insert  cases
    INSERT INTO TAB4
                    A,B,C
    SELECT
                                    A,BC
    FROM XYZ
    INSERT INTO TAB3
                    A,B,C
    SELECT
                                    A,BC
    FROM XYZ
    INSERT INTO TAB2
                    A,B,C
    SELECT
                                    A,BC
    FROM XYZ
    I will be using following to insert further insert statements 
    if @InsertCase =1 
    I just needed to know where will be my next insert statement should be fitting int his code so that i cover exception handling for all the code
    Mudassar

    Hi Erland & Mudassar, I have attempted to recreate Mudassar's original problem..here is my TABLE script;
    USE [MSDNTSQL]
    GO
    /****** Object: Table [dbo].[TAB1] Script Date: 2/5/2014 7:47:48 AM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[TAB1](
    [COL1] [nvarchar](1) NULL,
    [COL2] [nvarchar](1) NULL,
    [COL3] [nvarchar](1) NULL,
    [START_MONTH] [int] NULL,
    [END_MONTH] [int] NULL,
    [START_YEAR] [int] NULL,
    [END_YEAR] [int] NULL
    ) ON [PRIMARY]
    GO
    Then here is a CREATE script for the SPROC..;
    USE [MSDNTSQL]
    GO
    /****** Object: StoredProcedure [dbo].[TryCatchTransactions1] Script Date: 2/5/2014 7:51:33 AM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE PROCEDURE [dbo].[TryCatchTransactions1] (
    @IncrStartDate DATE
    ,@IncrEndDate DATE
    ,@SourceRowCount INT OUTPUT
    ,@TargetRowCount INT OUTPUT
    ,@ErrorNumber INT OUTPUT
    ,@ErrorMessage VARCHAR(4000) OUTPUT
    ,@InsertCase INT --INSERT CASE INPUT
    WITH
    EXEC AS CALLER AS
    BEGIN --Main Begin
    SET NOCOUNT ON
    BEGIN TRY
    DECLARE @SuccessNumber INT = 0
    ,@SuccessMessage VARCHAR(100) = 'SUCCESS'
    ,@BenchMarkLoadFlag CHAR(1)
    ,@BenchmarkFlow INT
    ,@MonthYearStart DATE
    ,@MonthYearEnd DATE
    ,@StartDate DATE
    ,@EndDate DATE
    /* Setting the default values of output parameters to 0.*/
    SET @SourceRowCount = 0
    SET @TargetRowCount = 0
    /*Setting the Start and end date for looping */
    SET @MonthYearStart = @IncrStartDate;
    SET @MonthYearEnd = @IncrEndDate;
    /* Setting the @InsertCase will ensure case wise insertion as this sp will load data in different tables
    @InsertCase =0 means data will be inserted in the target TAB1
    @InsertCase =1 means data will be inserted in the target TAB2
    @InsertCase =2 means data will be inserted in the target TAB3
    @InsertCase =3 means data will be inserted in the target TAB4
    @InsertCase =4 means data will be inserted in the target TAB5
    @InsertCase =5 means data will be inserted in the target TAB6
    IF @InsertCase =0
    WHILE (@MonthYearStart <= @MonthYearEnd)
    BEGIN
    SET @StartDate = @MonthYearStart;
    SET @EndDate = @MonthYearEnd;
    /* Delete from target where date range given from input parameter*/
    DELETE FROM TAB1
    WHERE START_MONTH BETWEEN MONTH(@StartDate) AND MONTH(@EndDate)
    AND START_YEAR BETWEEN year(@StartDate) and YEAR(@EndDate)
    /*Insert data in target-TAB1 */
    BEGIN TRANSACTION
    INSERT INTO TAB1 (COL1,COL2,COL3)
    VALUES ('Z','X','Y')
    SELECT COL1, COL2, COL3
    FROM TAB1
    COMMIT TRANSACTION
    SET @MonthYearStart = DATEADD(MONTH, 1, @MonthYearStart)
    SELECT @TargetRowCount = @TargetRowCount + @@ROWCOUNT;
    END -- End of whileloop
    END TRY
    BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION
    SELECT @ErrorNumber = ERROR_NUMBER() ,@ErrorMessage = ERROR_MESSAGE();
    END CATCH
    PRINT @SUCCESSMESSAGE
    END--End of Main Begin
    GO
    I am just trying to help --danny rosales
    UML, then code

Maybe you are looking for

  • URG:11i to R12.1.3: Invoice print Selected Invoices fails with REP-1419

    Hi, Invoice print Selected Invoices fails with the following error: Forcing NLS_NUMERIC_CHARACTERS to: '.,' for XDO processing APPLLCSP Environment Variable set to : Current NLS_LANG and NLS_NUMERIC_CHARACTERS Environment Variables are : American_Ame

  • Can multiple remote desktops control the same machine at the same time?

    Can anyone please tell me if this set up possible: mac mini running XP app iMac logged into to control that app ibook logged in to control that app of course, only one person actually moving the mouse / using the keyboard at one time. Miklos.

  • Templates link to template folder

    hi. I not used to using dreamweaver. I would MUCH rather write html by hand. but my boss uses DreamWeaver and I am trying to update a template that he made. so he created a "site" in dreamweaver so it put all his files in its own structure and all. b

  • Cannot mount burned DVD

    I have a Memorex DVD+R disc with video burned to it from a consumer DVD player/recorder. The disc has been finalized but will not appear on any other DVD player (it plays fine of the machine it was recorded on but takes several minutes to actually lo

  • How to use Microsoft SSIS to communicate with SAP Extractors? Is XI a way?

    Hello Extraction Experts! here is a challange for you: Our customer wants to pull GL Data from ECC6 as well as other various R3 Special Ledgers into a database (Not SAP BW at this point in time!), which can then provide the data to a 3rd party tax ca