Purpose of throws clause in exception handling

hi all,
I have written a sample code for exception handling...please refer below....
class a
void fun() throws ArithmeticException
int i=0;
i=10/0;
class exec
public static void main(String a[])
a a1=new a();
     try{a1.fun();}
     catch(ArithmeticException e){System.out.println("hi");}
}

I read the article...and came out with these points...
1..If method is throwing an unchecked exception (as in this case) then there is no need for throws clause, if you are not catching it then and there only.....
2...if a method is throwing a checked exception then either you need to catch it then and there only or you must specify a throws clause for the same in function definition......*And the purpose of not catching it then and there only is*
"For example, if you were providing the ListOfNumbers class as part of a package of classes, you probably couldn't anticipate the needs of all the users of your package. In this case, it's better to not catch the exception and to allow a method further up the call stack to handle it."
M I RIGHT??

Similar Messages

  • Generic throws clause causes unreported exception

    I'm trying to pass a block to a ctor, which can throw an exception. The problem can be reproduced with this sample program.
    interface Bar<X extends Exception> {
        void run() throws X;
    public class Foo {
        public Foo() {}
        public <X extends Exception> Foo(Bar<X> bar) throws X {
            bar.run();
        public static <X extends Exception> Foo createFoo(Bar<X> bar) throws X {
            return createFoo2(bar); // ok
        public static <X extends Exception> Foo createFoo2(Bar<X> bar) throws X {
            Foo foo = new Foo();
            bar.run(); // ok
            return foo;
        public static <X extends Exception> Foo createFoo3(Bar<X> bar) throws X {
            return new Foo(bar);  // unreported exception X; must be caught or declared to be thrown
    }createFoo and createFoo2 work fine, but createFoo3 fails to compile with javac. None of the examples raise a warning in IDEA. I'm running javac 1.5.0_07.
    Is there a way to do this in Java 1.5, or is this a bug with javac?

    BrianEgge wrote:
    However, we know types inference works differently for methods vs constructors (15.12.2.8). This is why List<String> s = Collections.emptyList(); works, but List<String> s = new ArrayList<String>() generates an unchecked warning. Well, this is definitely not true.
    According the the JLS, the throws clause shouldn't be handled differently.
    8.8.5 Constructor Throws
    The throws clause for a constructor is identical in structure and behavior to the throws clause for a method (�8.4.6).The JLS explicitely allows a constructor to be defined generic, and those parameters have a scope on the constructor definition including the parameter list (8.8.4 Generic Constructors).
    Hence, I assume, this is a bug.

  • Exception Handling Standards -The exception Exception should never been thrown. Always Subclass Exception and throw the subclassed Classes.

    In the current project my exception handling implementation is as follows :
    Exception Handling Layer wise :
    DL layer :
    catch (Exception ex)
    bool rethrow = ExceptionPolicy.HandleException(ex, "Ui Policy");
    if (rethrow)
    throw;
    BL Layer
    catch (Exception ex)
    bool rethrow = ExceptionPolicy.HandleException(ex, "Ui Policy");
    if (rethrow)
    throw;
    UI Layer
    catch (Exception ex)
    bool rethrow = ExceptionPolicy.HandleException(ex, "Ui Policy");
    if (rethrow)
    Response.Redirect("ErrorPage.aspx", false);
    We have a tool to check the standards. And tool output is as follows :
    The exception Exception should never been thrown. Always Subclass Exception and throw the subclassed Classes.
    I need suggestions on how to implement the same according to standards.

    Your tool is wrong if it says to never throw Exception.  This was a common recommendation back in the .NET v1 days but has long since been thrown out.  It is perfectly fine to use Exception when you have a general exception that provides no information
    that an application can use to make an informed opinion.
    The general rules of exception throwing is to throw the most specific exception that makes sense. If there is no specific exception that applies and it would be useful for the caller to handle the exception differently than other exceptions then creating
    a custom exception type is warranted.  Otherwise throwing Exception is reasonable. As an example you might have an application that pulls back product data given an ID. There is no built in exception that says the ID is invalid. However an invalid ID
    is something that an application may want to handle differently than, say, an exception about the product being discontinued.  Therefore it might make sense to create an ItemNotFoundException exception that the application can react to.
    Conversely there is no benefit in having different exception types for disk full and disk quota met. The application will respond the same in either case.
    Michael Taylor
    http://blogs.msmvps.com/p3net

  • What is the Use of throws in Exception Handling

    I have clear idea about try,catch,finally, but i do not have clear idea about throws
    Can u anyone explain about throws with example program?
    Thanks

    >
    I have clear idea about try,catch,finally, but i do not have clear idea about throws
    Can u anyone explain about throws with example program?
    >
    Yes - the Java Tutorial can explain it and has examples
    http://docs.oracle.com/javase/tutorial/essential/exceptions/
    And all of the Java Language constructs, including 'throws' are defined in the Java Language Specification
    http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.4.6
    >
    8.4.6. Method Throws
    A throws clause is used to declare any checked exception classes (§11.1.1) that the statements in a method or constructor body can throw (§11.2.2).

  • AbstractTable model exception throws clause error?

    I want to display a JDialog whenever the user tries to enter a string when the column class is Double. To do this, I am trying to throw an exception from the setValueAt() method in my class that extends AbstractTable model. However, my code results in an "Exception StatisticsException is not compatible with throws clause in AbstractTableModel.setValueAt()". Any idea how I can work around this? Is there a better way to display a JDialog in this case? Thanks in advance.
    public void setValueAt(Object text, int rowIndex, int columnIndex)throws StatisticsException{
             if(variables[columnIndex].isDouble()){
                  try{
                       Double.parseDouble(text.toString());
                       Object[] temp = data.get(rowIndex);
                       temp[columnIndex] = text.toString();
                       data.remove(rowIndex);
                       data.add(rowIndex, temp);
                  }catch(NumberFormatException ex){
                       throw new StatisticsException("Numeric value required.");
             }else{
                  Object[] temp = data.get(rowIndex);
                  temp[columnIndex] = text.toString();
                  data.remove(rowIndex);
                  data.add(rowIndex, temp);
        }

    Ah, yes of course. In the midst of trying to account for data entry errors, I forgot that. The following revised code works just fine. Thanks.
        public void setValueAt(Object text, int rowIndex, int columnIndex){
              Object[] temp = data.get(rowIndex);
              temp[columnIndex] = text.toString();
              data.remove(rowIndex);
              data.add(rowIndex, temp);
        }

  • Javadoc @throws clause at a class level for all methods

    hello
    If all my class's methods throw the same RuntimeException for the same reasons, is there a way to put a @throws clause at class level?
    I mean, I don't want to duplicate my comments for each of the methods I have. Say I want to add extra information... It would be a pain to copy paste same
    comment for all the methods.
    Thx in advance, any help welcomed :)

    kux wrote:
    hello again
    first of all, love your replay :). Nice to see people with good sense of humor :D
    Ok, I made the story shorter. Of course I don't throw a raw RuntimeException. What I have is a subclass of RuntimeException. Basicly all my methods use a sql Connection and do a certain querry on a database. What I do is that I don't let checked SQLException propagate through my methods because the clients of the persistance layer should not be required to handle the low level sql exeptions.Correct!
    Instead I catch them and rethrow them as DAOExceptions that SUBCLASS RuntimeException. Unusual... but... Hmmm... I can't say that's actually "bad practice", per se, but DAOException is traditionally a checked exception type thrown only from the very top of the DAO specifically so that clients must catch (or explicitly throw) it... Hmmm..
    Basicly I used sun's DAO pattern: http://java.sun.com/blueprints/patterns/DAO.html.
    That's be The GOF's pattern... but yeah, good choice.
    I made the question shorter because this is not the point. The question was about javadoc, not my programming practices :)But, but, but...
    Ok... Ah... Ok.... Ummm, No. At least Not That I Know Of... BUT, what you can do is summarise your exception handling strategy once in the class summary section, and just reference it in each throws clause... you can stick intra-page links in java doc (I've seen them, just not sure how they're done, I think the syntax is something like {@link:anchor}... but that's just something I once saw somewhere... not gospel.
    Also, if a method has throws DAOExceptions for an "odd" reason (like invalid data retrieved successfuly from the database (yes, it happens)) then you can still document that case in the method.
    If your exception handling is really worth talking about then an external article referenced in the class summary. We use a wiki (http://en.wikipedia.org/wiki/DokuWiki) for such purposes, and many others including research schedules and papers, and (increasingly) design doco, even though that's outside the "official process" we find the wiki so much more convenient (i.e. searchable), especially since it's become possible to convert (simple) word-doc's straigth to wiki markup.
    But, but, but... Programming practices are so much more interesting than documentation... who ever complained about in the documentation (besides me I mean).
    Cheers mate. Keith.

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

  • Exception handling in JSF

    This question has been asked time and again, without any clear answers to it. I would appreciate if some one can help me on this.
    I am developing a web application with the following architecture:
    JSF page calls backing bean methods which calls the service methods. Now my service methods can throw different exceptions like ValidationException, BusinessException, SystemException etc.
    Now, what i want to do is : If Validation/Business Exceptions are thrown show the error messages to the user on the same page from which the action was called. And if a SystemException is thrown navigate to a default error page.
    How can i handle this thing? Any clues?

    Thanks for the reply BalusC,
    I checked the log files (application log as well as server log) also and there is no other stack trace besides of the exception which i am throwing. Let me elaborate on the exact issue:
    I am trying to handle concurrency issues in my application. For example, When two users simultaneously try to edit the same record, the user who first saves the changes successfully. Now when the second user tries to save the changes i want to show him a message that "This record has been modified after you opened it for edit. Please refresh your page and reapply the changes". To show this message i am throwing a BusinessException from my service, which in turn gets propagated to my saveAction method. The saveAction method needs to handle this exception and somehow should show the above message to the user.
    To achieve this,
    1. i tried catching the exception in my saveAction and added the necessary faces message to FacesContext object. But it does not work. Later i read the reason behind this too, that in the invoke application phase a new context will be created and the messages will not be available to it.
    2. I then added the throws clause to my saveAction method, so that my default exception handler will handle it.
    saveAction method signature :
    public String saveAction () throws BusinessException {
        //some code here for save
        return null;
    }This is my code for the ErrorHandler.jsp:
    <body>
            <h1 style="color: red">Error</h1><br/><%
                 // print stack trace.
                ExceptionHandler exceptionHandler = new ExceptionHandler();
                 // unwrap ServletExceptions.
                while (exception instanceof ServletException || exception instanceof FacesException ||
                        exception instanceof ApplicationException) {
                    if(exception instanceof ServletException) {
                        exception = ((ServletException) exception).getRootCause();
                    } else if(exception instanceof FacesException) {
                        exception = ((FacesException) exception).getCause();
                    } else if(exception instanceof ApplicationException) {
                        exception = ((ApplicationException) exception).getCause();
      %><font color="red"><%=exceptionHandler.handleException(exception)%></font><br/></body>and this is my code for the handleException method defined in the ExceptionHandler.java:
    public static String getMessage(final String msgKey, final Object args[]) {
            String message = messages.getProperty(msgKey);
            if(args != null) {
                final String replaceArgs[] = (String[]) args;
                for(int i = 0; i < replaceArgs.length; i++)
                    message = message.replaceFirst("{" + i + "}", replaceArgs);
    return message;
    public String handleException(final Throwable exception) {
    logger.debug("handleException called..");
    String errorMessage = "Unknown error occured.";
    String stackTrace = "Stacktrace can not be found. Please check the logs for more details.";
    String errorString = null;
    final StringWriter stringWriter = new StringWriter();
    if(exception != null) {
    exception.printStackTrace (new PrintWriter (stringWriter));
    stackTrace = stringWriter.toString();
    errorMessage = getMessage(exception.getMessage(), null);
    errorString = "<b>" + errorMessage + "</b> <br> </br> <br> <input id=\"show\" type=\"button\" value=\"Show Details >>\" onClick=\"toggle();\" /> <div id=\"errorStackTrace\" style=\"display:none;\" > <pre>" + stackTrace + "</pre> </div>";
    return errorString;
    With the help of this code, i am simply trying to navigate to the error page if an exception occurs and display the appropriate error message with the stacktrace.
    The strange thing is, the ErrorHandler.jsp page correctly gets called, which in turn calls the handleException method which returns the formatted error string. (I checked this by adding log statements everywhere). But the system does not actually navigates to the ErrorHandler.jsp page and shows an alert with the following message : "Request error, status : 500 Internal Server Error message : "
    Can someone help me figure out what exactly the problem is?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Removing Exception Handling Causes Compiler Error

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

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

  • ADF Faces: Exception Handler activity ain't reraised

    Hi there!
    I'm using a Studio Edition Version 11.1.1.3.0 (Build JDEVADF_11.1.1.3.PS2_GENERIC_100408.2356.5660).
    I've done this:
    1. created a bounded task flow flow1 and added to it:
    1.1 a vew activity view1 (the default activity) - shows an inputText field for a db column, for which there is a constraint;
    1.2 a method call activity method1 - calls commit;
    1.3 a view activity view2 - has an ouputText depicting an attribute's value for the same collection as that of inputText in view1;
    1.4 a view activity errorView (marked as an exception handler) - displays a localizedMessage from the currentViewPort;
    1.5 created for the view activities page fragments (with necessary fields and buttons).
    2. linked them as follows:
    2.1 view1 -*-> method1 -*-> view2;
    2.2 errorView -*-> view1.
    3. in the default unbounded task flow created a view activity main, a page file for it, and dropped onto the latter the flow1 as a region;
    4. launched the app (as the table contains some data, the view1 displays first row in a row set);
    5. entered into the view1 's field a non-violating value;
    6. pressed a button (which has just an action property set to move to the method1 ) - everything's fine, we get to the view2;
    6. rerun the app;
    7. entered incorrect value, pressed the button - flow goes, as expected, to the errorView, which informs us the exception's details (JBO-...);
    8. on the errorView page fragment pressed a button - we are now on the view1 page again;
    9. left the wrong (violating) value (or changed it to another incorrect value, doesn't matter) and pressed the button again;
    10. wow, we reached the view2, but, I guess, we hadn't to. Why so?
    One must note, that in clauses 7 and 9, after pressing the button, there apears a popup, which advises us about an ORA-... error, that is, in step 9 the ADF Faces does receive the exception, but why it doesn't reraise the errorView, that's the question.
    Though, when I change the method1 so, that it calls a bean's method, which always throws an IllegalArgumentException, then everything works as should to - we get to the infinite loop - view1 -> method1 -> errorView -> view1.
    Or, when I extract view2 from flow1, and instead of the former insert return activity with End Transaction set to commit, and then wrap (i.e call) flow1 from a newly created bounded task flow flow2, and in main 's page replace flow1 with flow2 region, the result is quite different. The aforesaid popup with ORA- error arises, until one enters a non-violating value. That is in this case everything is good, except, that control never flows into the errorView.
    And there is one more thing to note yet. When I've, namely method1, been calling a bean with the ever exception throwing method, the Integrated WLS's log was silent, but when the method1 was calling commit, then in the log we can see this twice:
    <Utils><buildFacesMessage> ADF: Adding the following JSF error message: ORA-02290: check constraint CHECK(THE_USER.THE_CONSTRAINT) violated
    java.sql.SQLIntegrityConstraintViolationException: ORA-02290: check constraint CHECK(THE_USER.THE_CONSTRAINT) violated
         at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:85)
         at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:133)
         at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:206)
         at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:455)
         at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:413)
         at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:1035)
         at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:194)
         at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:953)
         at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1224)
         at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3386)
         at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:3467)
         at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeUpdate(OraclePreparedStatementWrapper.java:1350)
         at oracle.jbo.server.OracleSQLBuilderImpl.doEntityDML(OracleSQLBuilderImpl.java:429)
         at oracle.jbo.server.EntityImpl.doDML(EntityImpl.java:8044)
         at oracle.jbo.server.EntityImpl.postChanges(EntityImpl.java:6373)
         at oracle.jbo.server.DBTransactionImpl.doPostTransactionListeners(DBTransactionImpl.java:3172)
         at oracle.jbo.server.DBTransactionImpl.postChanges(DBTransactionImpl.java:2980)
         at oracle.jbo.server.DBTransactionImpl.commitInternal(DBTransactionImpl.java:2018)
         at oracle.jbo.server.DBTransactionImpl.commit(DBTransactionImpl.java:2277)
         at oracle.adf.model.bc4j.DCJboDataControl.commitTransaction(DCJboDataControl.java:1577)
         at oracle.adf.model.binding.DCDataControl.callCommitTransaction(DCDataControl.java:1404)
         at oracle.jbo.uicli.binding.JUCtrlActionBinding.doIt(JUCtrlActionBinding.java:1427)
         at oracle.adf.model.binding.DCDataControl.invokeOperation(DCDataControl.java:2141)
         at oracle.jbo.uicli.binding.JUCtrlActionBinding.invoke(JUCtrlActionBinding.java:730)
         at oracle.adf.controller.v2.lifecycle.PageLifecycleImpl.executeEvent(PageLifecycleImpl.java:394)
         at oracle.adfinternal.view.faces.model.binding.FacesCtrlActionBinding._execute(FacesCtrlActionBinding.java:252)
         at oracle.adfinternal.view.faces.model.binding.FacesCtrlActionBinding.execute(FacesCtrlActionBinding.java:210)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:597)
         at com.sun.el.parser.AstValue.invoke(AstValue.java:157)
         at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:283)
         at oracle.adf.controller.internal.util.ELInterfaceImpl.invokeMethod(ELInterfaceImpl.java:168)
         at oracle.adfinternal.controller.activity.MethodCallActivityLogic.execute(MethodCallActivityLogic.java:161)
         at oracle.adfinternal.controller.engine.ControlFlowEngine.executeActivity(ControlFlowEngine.java:989)
         at oracle.adfinternal.controller.engine.ControlFlowEngine.doRouting(ControlFlowEngine.java:878)
         at oracle.adfinternal.controller.engine.ControlFlowEngine.doRouting(ControlFlowEngine.java:777)
         at oracle.adfinternal.controller.engine.ControlFlowEngine.routeFromActivity(ControlFlowEngine.java:551)
         at oracle.adfinternal.controller.engine.ControlFlowEngine.performControlFlow(ControlFlowEngine.java:147)
         at oracle.adfinternal.controller.application.NavigationHandlerImpl.handleAdfcNavigation(NavigationHandlerImpl.java:109)
         at oracle.adfinternal.controller.application.NavigationHandlerImpl.handleNavigation(NavigationHandlerImpl.java:78)
         at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:130)
         at org.apache.myfaces.trinidad.component.UIXCommand.broadcast(UIXCommand.java:190)
         at oracle.adf.view.rich.component.fragment.UIXRegion.broadcast(UIXRegion.java:148)
         at oracle.adfinternal.view.faces.lifecycle.LifecycleImpl.broadcastEvents(LifecycleImpl.java:812)
         at oracle.adfinternal.view.faces.lifecycle.LifecycleImpl._executePhase(LifecycleImpl.java:292)
         at oracle.adfinternal.view.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:177)
         at javax.faces.webapp.FacesServlet.service(FacesServlet.java:265)
         at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227)
         at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125)
         at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:300)
         at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:26)
         at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
         at oracle.adf.model.servlet.ADFBindingFilter.doFilter(ADFBindingFilter.java:191)
         at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
         at oracle.adfinternal.view.faces.webapp.rich.RegistrationFilter.doFilter(RegistrationFilter.java:97)
         at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl$FilterListChain.doFilter(TrinidadFilterImpl.java:420)
         at oracle.adfinternal.view.faces.activedata.AdsFilter.doFilter(AdsFilter.java:60)
         at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl$FilterListChain.doFilter(TrinidadFilterImpl.java:420)
         at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl._doFilterImpl(TrinidadFilterImpl.java:247)
         at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl.doFilter(TrinidadFilterImpl.java:157)
         at org.apache.myfaces.trinidad.webapp.TrinidadFilter.doFilter(TrinidadFilter.java:92)
         at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
         at oracle.security.jps.ee.http.JpsAbsFilter$1.run(JpsAbsFilter.java:94)
         at java.security.AccessController.doPrivileged(Native Method)
         at oracle.security.jps.util.JpsSubject.doAsPrivileged(JpsSubject.java:313)
         at oracle.security.jps.ee.util.JpsPlatformUtil.runJaasMode(JpsPlatformUtil.java:414)
         at oracle.security.jps.ee.http.JpsAbsFilter.doFilter(JpsAbsFilter.java:138)
         at oracle.security.jps.ee.http.JpsFilter.doFilter(JpsFilter.java:71)
         at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
         at oracle.adf.library.webapp.LibraryFilter.doFilter(LibraryFilter.java:159)
         at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
         at oracle.dms.wls.DMSServletFilter.doFilter(DMSServletFilter.java:330)
         at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
         at weblogic.servlet.internal.RequestEventsFilter.doFilter(RequestEventsFilter.java:27)
         at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
         at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.doIt(WebAppServletContext.java:3684)
         at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3650)
         at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
         at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:121)
         at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2268)
         at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2174)
         at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1446)
         at weblogic.work.ExecuteThread.execute(ExecuteThread.java:201)
         at weblogic.work.ExecuteThread.run(ExecuteThread.java:173)What I'm doing wrong? And how can I dismiss that popup, as it duplicates errorView and does not get messages from a custom message bundle?
    Thanks in advance for any comments.
    Yerzhan.

    Hi there!
    I'm using a Studio Edition Version 11.1.1.3.0 (Build JDEVADF_11.1.1.3.PS2_GENERIC_100408.2356.5660).
    I've done this:
    1. created a bounded task flow flow1 and added to it:
    1.1 a vew activity view1 (the default activity) - shows an inputText field for a db column, for which there is a constraint;
    1.2 a method call activity method1 - calls commit;
    1.3 a view activity view2 - has an ouputText depicting an attribute's value for the same collection as that of inputText in view1;
    1.4 a view activity errorView (marked as an exception handler) - displays a localizedMessage from the currentViewPort;
    1.5 created for the view activities page fragments (with necessary fields and buttons).
    2. linked them as follows:
    2.1 view1 -*-> method1 -*-> view2;
    2.2 errorView -*-> view1.
    3. in the default unbounded task flow created a view activity main, a page file for it, and dropped onto the latter the flow1 as a region;
    4. launched the app (as the table contains some data, the view1 displays first row in a row set);
    5. entered into the view1 's field a non-violating value;
    6. pressed a button (which has just an action property set to move to the method1 ) - everything's fine, we get to the view2;
    6. rerun the app;
    7. entered incorrect value, pressed the button - flow goes, as expected, to the errorView, which informs us the exception's details (JBO-...);
    8. on the errorView page fragment pressed a button - we are now on the view1 page again;
    9. left the wrong (violating) value (or changed it to another incorrect value, doesn't matter) and pressed the button again;
    10. wow, we reached the view2, but, I guess, we hadn't to. Why so?
    One must note, that in clauses 7 and 9, after pressing the button, there apears a popup, which advises us about an ORA-... error, that is, in step 9 the ADF Faces does receive the exception, but why it doesn't reraise the errorView, that's the question.
    Though, when I change the method1 so, that it calls a bean's method, which always throws an IllegalArgumentException, then everything works as should to - we get to the infinite loop - view1 -> method1 -> errorView -> view1.
    Or, when I extract view2 from flow1, and instead of the former insert return activity with End Transaction set to commit, and then wrap (i.e call) flow1 from a newly created bounded task flow flow2, and in main 's page replace flow1 with flow2 region, the result is quite different. The aforesaid popup with ORA- error arises, until one enters a non-violating value. That is in this case everything is good, except, that control never flows into the errorView.
    And there is one more thing to note yet. When I've, namely method1, been calling a bean with the ever exception throwing method, the Integrated WLS's log was silent, but when the method1 was calling commit, then in the log we can see this twice:
    <Utils><buildFacesMessage> ADF: Adding the following JSF error message: ORA-02290: check constraint CHECK(THE_USER.THE_CONSTRAINT) violated
    java.sql.SQLIntegrityConstraintViolationException: ORA-02290: check constraint CHECK(THE_USER.THE_CONSTRAINT) violated
         at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:85)
         at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:133)
         at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:206)
         at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:455)
         at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:413)
         at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:1035)
         at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:194)
         at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:953)
         at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1224)
         at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3386)
         at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:3467)
         at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeUpdate(OraclePreparedStatementWrapper.java:1350)
         at oracle.jbo.server.OracleSQLBuilderImpl.doEntityDML(OracleSQLBuilderImpl.java:429)
         at oracle.jbo.server.EntityImpl.doDML(EntityImpl.java:8044)
         at oracle.jbo.server.EntityImpl.postChanges(EntityImpl.java:6373)
         at oracle.jbo.server.DBTransactionImpl.doPostTransactionListeners(DBTransactionImpl.java:3172)
         at oracle.jbo.server.DBTransactionImpl.postChanges(DBTransactionImpl.java:2980)
         at oracle.jbo.server.DBTransactionImpl.commitInternal(DBTransactionImpl.java:2018)
         at oracle.jbo.server.DBTransactionImpl.commit(DBTransactionImpl.java:2277)
         at oracle.adf.model.bc4j.DCJboDataControl.commitTransaction(DCJboDataControl.java:1577)
         at oracle.adf.model.binding.DCDataControl.callCommitTransaction(DCDataControl.java:1404)
         at oracle.jbo.uicli.binding.JUCtrlActionBinding.doIt(JUCtrlActionBinding.java:1427)
         at oracle.adf.model.binding.DCDataControl.invokeOperation(DCDataControl.java:2141)
         at oracle.jbo.uicli.binding.JUCtrlActionBinding.invoke(JUCtrlActionBinding.java:730)
         at oracle.adf.controller.v2.lifecycle.PageLifecycleImpl.executeEvent(PageLifecycleImpl.java:394)
         at oracle.adfinternal.view.faces.model.binding.FacesCtrlActionBinding._execute(FacesCtrlActionBinding.java:252)
         at oracle.adfinternal.view.faces.model.binding.FacesCtrlActionBinding.execute(FacesCtrlActionBinding.java:210)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:597)
         at com.sun.el.parser.AstValue.invoke(AstValue.java:157)
         at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:283)
         at oracle.adf.controller.internal.util.ELInterfaceImpl.invokeMethod(ELInterfaceImpl.java:168)
         at oracle.adfinternal.controller.activity.MethodCallActivityLogic.execute(MethodCallActivityLogic.java:161)
         at oracle.adfinternal.controller.engine.ControlFlowEngine.executeActivity(ControlFlowEngine.java:989)
         at oracle.adfinternal.controller.engine.ControlFlowEngine.doRouting(ControlFlowEngine.java:878)
         at oracle.adfinternal.controller.engine.ControlFlowEngine.doRouting(ControlFlowEngine.java:777)
         at oracle.adfinternal.controller.engine.ControlFlowEngine.routeFromActivity(ControlFlowEngine.java:551)
         at oracle.adfinternal.controller.engine.ControlFlowEngine.performControlFlow(ControlFlowEngine.java:147)
         at oracle.adfinternal.controller.application.NavigationHandlerImpl.handleAdfcNavigation(NavigationHandlerImpl.java:109)
         at oracle.adfinternal.controller.application.NavigationHandlerImpl.handleNavigation(NavigationHandlerImpl.java:78)
         at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:130)
         at org.apache.myfaces.trinidad.component.UIXCommand.broadcast(UIXCommand.java:190)
         at oracle.adf.view.rich.component.fragment.UIXRegion.broadcast(UIXRegion.java:148)
         at oracle.adfinternal.view.faces.lifecycle.LifecycleImpl.broadcastEvents(LifecycleImpl.java:812)
         at oracle.adfinternal.view.faces.lifecycle.LifecycleImpl._executePhase(LifecycleImpl.java:292)
         at oracle.adfinternal.view.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:177)
         at javax.faces.webapp.FacesServlet.service(FacesServlet.java:265)
         at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227)
         at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125)
         at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:300)
         at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:26)
         at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
         at oracle.adf.model.servlet.ADFBindingFilter.doFilter(ADFBindingFilter.java:191)
         at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
         at oracle.adfinternal.view.faces.webapp.rich.RegistrationFilter.doFilter(RegistrationFilter.java:97)
         at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl$FilterListChain.doFilter(TrinidadFilterImpl.java:420)
         at oracle.adfinternal.view.faces.activedata.AdsFilter.doFilter(AdsFilter.java:60)
         at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl$FilterListChain.doFilter(TrinidadFilterImpl.java:420)
         at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl._doFilterImpl(TrinidadFilterImpl.java:247)
         at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl.doFilter(TrinidadFilterImpl.java:157)
         at org.apache.myfaces.trinidad.webapp.TrinidadFilter.doFilter(TrinidadFilter.java:92)
         at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
         at oracle.security.jps.ee.http.JpsAbsFilter$1.run(JpsAbsFilter.java:94)
         at java.security.AccessController.doPrivileged(Native Method)
         at oracle.security.jps.util.JpsSubject.doAsPrivileged(JpsSubject.java:313)
         at oracle.security.jps.ee.util.JpsPlatformUtil.runJaasMode(JpsPlatformUtil.java:414)
         at oracle.security.jps.ee.http.JpsAbsFilter.doFilter(JpsAbsFilter.java:138)
         at oracle.security.jps.ee.http.JpsFilter.doFilter(JpsFilter.java:71)
         at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
         at oracle.adf.library.webapp.LibraryFilter.doFilter(LibraryFilter.java:159)
         at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
         at oracle.dms.wls.DMSServletFilter.doFilter(DMSServletFilter.java:330)
         at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
         at weblogic.servlet.internal.RequestEventsFilter.doFilter(RequestEventsFilter.java:27)
         at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
         at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.doIt(WebAppServletContext.java:3684)
         at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3650)
         at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
         at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:121)
         at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2268)
         at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2174)
         at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1446)
         at weblogic.work.ExecuteThread.execute(ExecuteThread.java:201)
         at weblogic.work.ExecuteThread.run(ExecuteThread.java:173)What I'm doing wrong? And how can I dismiss that popup, as it duplicates errorView and does not get messages from a custom message bundle?
    Thanks in advance for any comments.
    Yerzhan.

  • Never implemented exception handling  in Stored Procedures

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

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

  • Exception handling - more

    Okay, new day new questions.
    What's better?
    method ...() {
    try {
    doMethod1();
    catch (exception) {
    // handle error
    try {
    doMethod2();
    catch (exception) {
    // handle error
    }or
    method()...{
    try {
    doMethod1();
    doMethod2();
    catch (exception) {
    // handle exception
    }The question is readability and program flow. If you wrap up a chunk of a code block which contains methods that throw exceptions as well as those that don't, when you're reading back through it it's hard to know which methods throw exceptions and which don't. It's hard to see the flow of the program just by looking at the code.
    But if you wrap up every method in a try/catch that can throw an exception you make it just as hard to see the program flow since you're dealing with multiple exceptions where each catch handles the error in much the same way. Instead of breaking out of the method at one place you could now be breaking out at several.
    Comments? Suggestions?

    There's one more: don't catch anything and declare your method to throw them, that way the calling method gets thrown an exception containing not only a full stack trace but also a (supposedly) descriptive message.
    Of course we know that that is not always the case.
    I think the "best" way depends on circumstances. I was asked at a job interview, "How do you decide whether to catch and exceptions in a method or to have them throw 'em on up?". My answer was to stammer around a bit, then reply very cleverly with "It depends."
    HaHa, but I think it's true. It depends on the kind of program, the purpose of the method, and the potential uses of the method. (ps. the interviewer is now my boss, so maybe I was right?)
    A story from my past life: there was once a class/method, originally never intended to be used outside of its package and the single use they had in mind when they designed it. Unfortunately, time proved that this package has some useful stuff and it grew into kindof an widely used API within the company. However the class/method to which I refer was responsible for open a Socket connection (from an IP address string and string port number) to a device and communicating some bytes back and forth to initialize the device (can you count how many checked much less unchecked things can come out of that before you even do any validity checking???). However, this constructor caught all of its exceptions and handled them by writing to some logging system that existed only in the original system). Therefore, years later when I was writing a GUI that used this class, my GUI had no way of knowing if anything was wrong, much less what actually was wrong.
    The moral of the story is that I have come to believe in letting exceptions float up as high as reasonable, because you never know. (Of course I don't always practice this flawlessly.)
    /Mel

  • Delete Statement Exception Handling

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

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

  • Exception handling is not working in GCC compile shared object

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

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

  • Exception Handling Messages

    Hi,
    I am trying to code the program to:
    1. display the message in the no arg ctor "Invalid Dimension"
    2. display the message in the try block passing good values
    "height and width are valid "
    3. display the message in the try block passing bad values
    "height and width must be greater than zero"
    I have tried many different ways and can't figure it out. Can someone please
    help.
    Thanks
    import javax.swing.JApplet;
    import java.awt.Graphics;
    //A user defined exception must inherit from Throwable. 
    //Exception inherits from Throwable.
    class IllegalDimensionException extends Exception//*****
      //Exception class will see String
      public IllegalDimensionException()//no arg ctor
        super("Invalid Dimension");
      //Allows unique message to be created rather than using
      //no arg ctor message
      public IllegalDimensionException(String errmessage)//1 arg ctor
        super(errmessage);
    class Rectangle extends Shape 
          private static int counter = 0;
          private int width;
          private int height;
          Rectangle( )
             ++counter;
          Rectangle(int x, int y, int w, int h)
             super(x,y);
             width  = w;
             height = h;
          ++counter;
           public void setDimension(int w, int h) throws IllegalDimensionException
              if(h < 0 || w < 0)//*****
                 throw new IllegalDimensionException();//throw initiates an exception//*****
           width  =  w;
              height =  h;
           public void set(int x, int y, int w, int h)
              loc.set(x,y);
              width  = w;
              height = h;
            public int getWidth()   {return width;}
            public int getHeight()  {return height;}
            public int perimeter() 
               return (2 * width) + (2 * height);
            public double area()      
              return width * height;
         public void draw(Graphics g)
              g.drawRect(loc.getX(),loc.getY(),width,height);
         public String toString()
           return
              "(("+ loc.getX() +","+ loc.getY() +"),"+ width +","+ height +")";
         public static int recCount()
               return counter;
    public class FinalA8 extends JApplet
        Rectangle r1;
        Rectangle r2;
        Rectangle r3;
        Circle c1;
        Circle c2;    
        public void init()
            r1 = new Rectangle( );
            r1.set(300,50,50,40);
            r2 = new Rectangle(400,50,80,60);//x,y,width,height
            r3 = new Rectangle();
         public void paint(Graphics g)
            r3.setLocation(500,50);
            try//*****
              r3.setDimension(-3, 4);
            //catch uses 1 arg ctor
            catch(IllegalDimensionException e)//*****
              //System.out.println("height & width must be greater than zero");
            try//*****
              r3.setDimension(100, 150);
            catch(IllegalDimensionException e)//*****
              System.out.println("height & width are valid");
    }

    Thanks for your reply.
    I can't figure out these compile errors?
    C:\java>javac FinalA8.java
    FinalA8.java:346: ')' expected.
           catch(IllegalDimension Exception e)
                                           ^
    FinalA8.java:355: Type expected.
            ("r3:  xCoord =" + r3.getX() + "  yCoord=" + r3.getY()
             ^
    FinalA8.java:131: Exception IllegalDimensionException must be caught, or it must
    be declared in the throws clause of this constructor.
             setDimension(h,w);
                         ^
    FinalA8.java:150: Exception IllegalDimensionException must be caught, or it must
    be declared in the throws clause of this method.
              setDimension(h,w);
                          ^
    4 errors
    import javax.swing.JApplet;
    import java.awt.Graphics;
    //A user defined exception must inherit from Throwable. 
    //Exception inherits from Throwable.
    class IllegalDimensionException extends Exception//*****
      //Exception class will see String
      public IllegalDimensionException()//no arg ctor
        super("Invalid Dimension");
      //Allows unique message to be created rather than using
      //no arg ctor message
      public IllegalDimensionException(String errmessage)//1 arg ctor
        super(errmessage);
    class Rectangle extends Shape 
          private static int counter = 0;
          private int width;
          private int height;
          Rectangle( )
             ++counter;
          Rectangle(int x, int y, int w, int h)
              super(x,y);
              setDimension(h,w);
              ++counter;
           public void setDimension(int w, int h) throws IllegalDimensionException
              if(h < 0 || w < 0)//*****
                 throw new IllegalDimensionException();//throw initiates an exception//*****
           setDimension(h,w);
           public void set(int x, int y, int w, int h)
              loc.set(x,y);
              setDimension(h,w);
            public int getWidth()   {return width;}
            public int getHeight()  {return height;}
            public int perimeter() 
               return (2 * width) + (2 * height);
            public double area()      
              return width * height;
         public void draw(Graphics g)
              g.drawRect(loc.getX(),loc.getY(),width,height);
         public String toString()
           return
              "(("+ loc.getX() +","+ loc.getY() +"),"+ width +","+ height +")";
         public static int recCount()
               return counter;
    public class FinalA8 extends JApplet
        Rectangle r1;
        Rectangle r2;
        Rectangle r3;
        public void init()
            r1 = new Rectangle( );
            r2 = new Rectangle();
            r3 = new Rectangle();
         public void paint(Graphics g)
            r1.setLocation(300,50);
            r2.setLocation(400,50);
            r3.setLocation(500,50);
            try//*****
              r1.setDimension(-3, 4);
            //catch uses 1 arg ctor and prints message below
            catch(IllegalDimensionException e)//*****
              System.out.println("height & width must be greater than zero");
            try//*****
              r2.setDimension(100, 150);
            //catch uses 1 arg ctor and prints message below
            catch(IllegalDimensionException e)//*****
              System.out.println("Width and Height are valid");
           try//*****
             r3.setDimension(-0,-0);
           //catch uses 1 arg ctor and prints message in no arg ctor
           catch(IllegalDimension Exception e)
             System.out.println(e);}
            g.drawString
            ("r3: xCoord =" + r3.getX() + "  yCoord=" + r3.getY()
             + "  Width =" + r3.getWidth()
             + "  Height=" + r3.getHeight(), 20,150);
            g.drawString
             ("r's created:  "+Rectangle.recCount(),20,175);
            r1.draw(g);
            r2.draw(g);
            r3.draw(g);
     

Maybe you are looking for

  • Cluster failure and don`t start

    Hi. First, one of cluster node is lost Witness share. After reboot servers cluster service do not started. In Event Viewer write some errors: Event ID: 1090 The Cluster service cannot be started. An attempt to read configuration data from the Windows

  • Gray Startup Question Mark.  I've tried everything!

    Ok, so my Mac has been running slightly slow these past couple days, nothing I thought I should worry about, until today when I tried to restart it, it would not start up.  It would come up with the gray screen and apple logo then just shut off.  The

  • How to see no of boms in plant

    how to see no of boms in plant

  • What is the best report generator for flex?

    Anyone have idea

  • Missing audio waveforms in GarageBand 10.0.1

    My GarageBand 10.0.1 does not create audio waveforms when I record. I can record and play back my voice, but I don't see any audio waveforms when I record or playback. I must be missing some really elemental step, but for the life of me I can't figur