Exception Handling Within Methods

I'm currently looking over exception handling within Java and have what whats probably a very simple question to answer!
If within a method I have a try and catch block to handle all exceptions that the specific method may throw, do I then also need to specify the exceptions that the method will throw within its signature? (As I have already handled them).

After a bit more reading I think i've found my answer.
You only declare a method throws an exception if you wish to deal with it further up the method call stack. This raises another question though. If I did handle the exceptions that my method could throw within the method itself as well as declaring the method to throw the exceptions within its signature. What would happen?

Similar Messages

  • Exception handling within a value-binding expression

    Hi all,
    Forgive me if this question seems odd, but I am a long-time Struts developer, new to JSF.
    In Struts, exception handling was easy because all requests were funnelled through some subclass of Action. Exception handling could effectively be consolidated into one spot by applying the template-method pattern.
    Of course, with JSF, this is not possible because method names in value-binding and action-binding expressions can be chosen arbitrarily. For this reason, I am exploring aspect-oriented (and other) techniques for consolidation JSF exception handling into one spot, but rather than focus too intently on that, it's clear that I first need the ability to forward to an error page when an exception is encountered in a value-binding or action-binding expression.
    For action-binding expressions, ExternalContext.dispatch("<view id>"); seems to work quite well, but I am unable to make the same work when in the context of a value-binding expression. This is probably attributed to the fact that at that point, I am in an entirely different phase of the JSF request processing lifecycle.
    What I'm looking to know is if anyone has a reliable means of forwarding to an error page within the context of a value-binding expression. Better yet, does anyone know a reliable way of forwarding to another view regardless of what phase you are in?
    If it makes a difference (and I think it does) the error page uses JSF as well, and uses the same layout (provided via custom tags courtesy of JSP 2.0 tag files), so some view components would have the same name as the page which encountered the error. This seems to get in the way of me simply defining the error page for a 500 in my web deployment descriptor.
    Thanks in advance to anyone with a working suggestion.
    -Kent

    Let me pose a purely hypothetical use case to demonstrate the problem:
    Imagine a page in an HR app, employeeDetails.jsp, that displays an always-up-to-date combo box which lists employee names and IDs. onChange triggers a form submit with the intention of simply posting back to this page, with various text boxes, etc. below updated to show all information for the selected employee.
    Obviously, with the requirement that the combo box always be up to date, it's clear that the getter invoked by the value-binding expression must access the database (not directly of course, but via a facade, application, then data-access layer). Any unexpected and unchecked exception in this chain would propagate back up to the getter method on the backing bean. I need to, at that point, log the exception (trivial) and forward to a user-friendly error page.
    I suppose I could put some contraint on myself that data access is only performed within ActionEvent handlers, but I'm not sure that's consistent with the JSF model in general, in fact it almost seems Struts-like in that I'd have to invoke some action before loading this form to build the up-to-date list for the combo box, shove it in request scope, where it's then available to the page indicated by the navigation rules. Submission of the form on the page in question would also need to result in rebuilding the up-to-date list. Now we're looking at firther propagation of code. I want to avoid this, so I am looking for a better way.

  • Exception handling writeObject method

    Hi,
    I serialize an object and write it to a file. I want to be sure that if an exception occurs at the method writeObject, i can surely delete the file I created.
              File file;
              ObjectOutputStream output;
              file = new File("test.ser");
    file.createNewFile();
              output = new ObjectOutputStream(new FileOutputStream(file));
              try {
                   output.writeObject(message);
              } catch (IOException e) {
                   // ....how to handle
    Should I do something like that "file.deleteOnExit()" if file exists, or what else?
    Thanks
    Cenkbah

    cenkbahtiyar wrote:
    Should I do something like that "file.deleteOnExit()" if file exists, or what else?That depends on what you want.
    The file is very likely to be unusable, if an IOException happens, so you might as well delete the file.
    But that's unlikely to be the only thing that you'd want to do. If this is part of a file->save action, then you'd want to tell the user that saving failed, for example.

  • Global Exception Handling

    How to set up global exception handling to provide user friendly messages to user?
    AFAIK there is no real global exception handing available for now in ADF. So I need some "tutorials" about exception handling in:
    - Model
    - Controller
    - View
    Thx
    Regards
    Zmeda

    refer this
    http://blogs.oracle.com/groundside/entry/adventures_in_adf_logging_part
    controller
    http://blogs.oracle.com/jdevotnharvest/entry/extending_the_adf_controller_exception_handler
    http://andrejusb.blogspot.com/2011/03/exception-handler-for-method-calls_19.html
    http://my.safaribooksonline.com/book/databases/oracle/9780071622547/introduction-to-oracle-adf-task-flows/ch04lev1sec7
    http://my.safaribooksonline.com/book/databases/oracle/9780071622547/working-with-unbounded-and-bounded-oracle-adf-task-flows/169

  • Understanding on Exception handling???

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

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

  • Error in Raising exceptions in a method and handling the same in the WF

    Hi All
    I tried to implement Raising exceptions in a method and handling the same in the workflow
    in the same way given in SAPtechnical site .
    1.by adding a error msg in exception parameter .
    2. if the select query fails, to fetch the agent then :exit_return 9001 'ztable name' space space space.
    3.in the Background activity in which this method is called there automatically one outcome appears ,and I hav acitvated that outcome and in that done what need to be done for that error handling - just send a mail to concern person .
    4. in the normal outcome of the activity , the step to be executed are there .
    but its not working , if exception come then the WF stuck there only . it do not follow the exception outcome .
    Kindly help me , How can I do the exception handly in WF.
    thanks & Regards
    Kakoli

    > That is usually the case - you catch an error in the underlying program and pass that back so the workflow can go into error.
    > You're doing it correctly.
    I don't think that's quite right.
    If you define an error/exception in a method, it is automatically mapped to an outcome of the step/task.
    If you activate that outcome, then you can handle the exception in a branch of the workflow.
    For example: 'Remote connection is down, please contact Basis'
    The step should only go into error if an outcome occurs that you have NOT activated.
    So the original question is valid. Please give some more information on what the error message is..
    chrs
    Paul

  • Exception handling for ProjectService methods in a new 2006 DI API

    Normally for other objects the Add() method returns error code and calling the GetLastError you get the description.
    AddProject(Project) method of ProjectService returns ProjectParams object.
    So the question is where to get the error code or what is the correct exception handling for that new methods in 2006 SDK.
    Thanks for any help.
    Tomas

    Hi all,
    I have a sceranio :
    I created the text field, text box, com bobox .etc, on new form or exist form.
    When I want to bind data into UDO, i use "DataBind.setBound"
    ex:"oEdit.DataBind.SetBound(True, "@SM_OMOR", "U_Room")"
    Can i bind the data to exist table on B1?
    ex: oEdit.DataBind.setBound(True, "OHEM", "firstName")
    Plz guid !
    Rgds !

  • 2007A: Exception handling for new ProjectService methods

    Normally for other objects the Add() method returns error code and calling the GetLastError you get the description.
    AddProject(Project) method of ProjectService returns ProjectParams object.
    So the question is where to get the error code or what is the correct exception handling for that new methods in 2006 SDK.
    Thanks for any help.
    Tomas

    Hi Thomas,
    For DI API services there is no return code as for the basic objects methods like Add, Update,...
    The only way is then to put try/catch blocks in your code and identify the error message with the Exception.Message property (same mechanism as we have for the UI API). No way to filter them by return code.
    Regards
    Trinidad.

  • Exception Handling in bounded taskflows - expected behaviour

    Hi,
    I'm currently reviewing exception handling in bounded task flows and some things does not seems to be very clear for me.
    (q1) Does it make sense that a bounded task flow calls a method (via a method activity) defined on the page definition of another page (outside of the BTF) by using a #{data.xxxmyPageDef.myMethodName.execute} EL expression?
    (q2) Is is correct to expect the application to execute the method marked as ExceptionHandler in the taskflow, whenever an exception occurs?
    (q3) I created 5 different scenarios where I call a service method which throws an exception, from within a page fragment of the BTF.
    (q3 – sc1) Call a service method through the binding layer of the current page (by using #{bindings.xxx.execute})
    Result: A dialog containing the exception message appears.
    This is what I expected. Althought, the exception handler method does not seems to be invoked.(q3 – sc2) Call a service method through a task flow method activity using #{bindings.xxx.execute}
    Result: A dialog containing the exception message appears.
    This is what I expected. Althought, the exception handler method does not seems to be invoked.(q3 – sc3) Call a service method through a task flow method activity using #{data.myPageFragementPagedef.xxx.execute} (accessing the pageDef of the page fragment)
    Result: Nothing happens.
    This is not what I expected. Although, the exception handler method does nog seems to be invoked, I expect the ADF Error Handler to create a FacesMessage.(q3 – sc4) Call a service method through a task flow method activity using #{data.myPageContainingThePageFragmentPageDef.xxx.execute} (accessing the page containing the BTF region)
    Result: Nothing happens.
    This is not what I expected. Although, the exception handler method does nog seems to be invoked, I expect the ADF Error Handler to create a FacesMessage. (q3 – sc5) Call a service method through a task flow method activity using #{data.aPageOutsideTheBTFPageDef.xxx.execute} (accessing a page outside the BTW)
    Result: Nothing happens.
    This is not what I expected. Although, the exception handler method does nog seems to be invoked, I expect the ADF Error Handler to create a FacesMessage. (q4) How can it be possible that – without an exception handler – exceptions occur when calling method activities, without the exceptions being translated to FacesMessages?
    Thanks in advance,
    Koen Verhulst
    JDeveloper 11.1.1.4

    Koen,
    +(q1) Does it make sense that a bounded task flow calls a method (via a method activity) defined on the page definition of another page (outside of the BTF) by using a #{data.xxxmyPageDef.myMethodName.execute} EL expression?+
    No. Exceptions should be handled locally.
    +(q2) Is is correct to expect the application to execute the method marked as ExceptionHandler in the taskflow, whenever an exception occurs?+
    Only for exceptions that are before Render Response. The Render Response Phase is not handled in ADFc. So exceptions that occur in managed beans may fall through
    +(q3) I created 5 different scenarios where I call a service method which throws an exception, from within a page fragment of the BTF.+
    +(q3 – sc1) Call a service method through the binding layer of the current page (by using #{bindings.xxx.execute}) Result: A dialog containing the exception message appears.+
    This is what I expected. Althought, the exception handler method does not seems to be invoked.
    The binding layer has an error handler you can override in the DataBinings.cpx file
    +(q3 – sc2) Call a service method through a task flow method activity using #{bindings.xxx.execute}+
    Result: A dialog containing the exception message appears.
    This is what I expected. Althought, the exception handler method does not seems to be invoked.
    Again, you use the binding layer to invoke the service
    +(q3 – sc3) Call a service method through a task flow method activity using #{data.myPageFragementPagedef.xxx.execute} (accessing the pageDef of the page fragment)+
    Result: Nothing happens.
    This is not what I expected. Although, the exception handler method does nog seems to be invoked, I expect the ADF Error Handler to create a FacesMessage.
    Never use such a call. Its bad practice as there is no guarantee the container you reference is active. Always have the method call activity have its own binding defined when accessing a method call activity. I know there are lots of example floating aroundthat you #{data ...} and many are from 10.1.3. This should be avoided alltogether though
    +(q3 – sc4) Call a service method through a task flow method activity using #{data.myPageContainingThePageFragmentPageDef.xxx.execute} (accessing the page containing the BTF region)+
    Result: Nothing happens.
    This is not what I expected. Although, the exception handler method does not seems to be invoked, I expect the ADF Error Handler to create a FacesMessage.
    Again, this is not a proper use of the ADF framework.
    +(q3 – sc5) Call a service method through a task flow method activity using #{data.aPageOutsideTheBTFPageDef.xxx.execute} (accessing a page outside the BTW)+
    Result: Nothing happens. This is not what I expected. Although, the exception handler method does nog seems to be invoked, I expect the ADF Error Handler to create a FacesMessage.
    accessing a page outside the BTW (!!!) This should ring a worst practices alarm on your laptop (obviously doesn't do it either)
    +(q4) How can it be possible that – without an exception handler – exceptions occur when calling method activities, without the exceptions being translated to FacesMessages?+
    Exceptions are not handled in a single place but stacked. The business service raises an exception and passes it to the binding layer if not handled. The binding layer handles the exception and if it can't passes it to ADFc. ADFc can handle this exception if it is not during Render Response.
    Bottom line: There is no single point of exception handling. So as a recommendation for best practices
    - Catch and handle exceptions as close as possible to their origins
    - If things can go wrong, thy will - use try/catch blocks in managed beans
    - Use an exception handling activity in all bounded task flows. In the case of task flow call activities being used exceptions can bubble up to the caller. However, this would take users out of their current application context
    - Exceptions not handled in ADFc can be intercepted by overriding the application task flow exception handler (used by the exception handler activities). This would give you a chance e.g. to handle issues during Render Response
    - Never fight the framework, never bend the framework: Don't use out of scope access to page definitions and resources. Exception handling is not a replacement for bad code practices (sorry for saying this, its not meant to be rude) :-)
    Though I don't have a qualified numbers of bugs open for exception handling in ADF between 11.1.1.4 and now (and some that are open), but there are issues reported in this area. If there is something that really feels wrong, please go ahead and file a bug and provide a test case for development to have a look. The Render Response issue, for example is something we are aware of and that is in discussion (afaik knows, there is a change in exception handling in JSF 2 that may have an impact to what we can do in ADFc).
    thanks
    Frank

  • Bounded Taskflow Exception Handler not working with Page Fragements

    I have one bounded - taskflow task-flow-definition
    <?xml version="1.0" encoding="windows-1252" ?>
    <adfc-config xmlns="http://xmlns.oracle.com/adf/controller" version="1.2">
      <task-flow-definition id="task-flow-definition">
        <default-activity>view1</default-activity>
        <managed-bean>
          <managed-bean-name>backing_main</managed-bean-name>
          <managed-bean-class>view.backing.Main</managed-bean-class>
          <managed-bean-scope>pageFlow</managed-bean-scope>
        </managed-bean>
        <managed-bean>
          <managed-bean-name>backing_view1</managed-bean-name>
          <managed-bean-class>view.backing.View1</managed-bean-class>
          <managed-bean-scope>pageFlow</managed-bean-scope>
        </managed-bean>
        <managed-bean>
          <managed-bean-name>backing_view2</managed-bean-name>
          <managed-bean-class>view.backing.View2</managed-bean-class>
          <managed-bean-scope>pageFlow</managed-bean-scope>
        </managed-bean>
        <exception-handler>view2</exception-handler>
        <view id="view1">
          <page>/view1.jsff</page>
        </view>
        <view id="view2">
          <page>/view2.jsff</page>
        </view>
        <use-page-fragments/>
      </task-flow-definition>
    </adfc-config>view1.jsff contains one command button, which calls one ActionListener
    <?xml version='1.0' encoding='windows-1252'?>
    <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1"
              xmlns:af="http://xmlns.oracle.com/adf/faces/rich">
      <af:commandButton text="commandButton 1" actionListener="#{pageFlowScope.backing_view1.callMyFunction}"
                        binding="#{pageFlowScope.backing_view1.commandButton1}"
                        id="commandButton1"/>
      <!--oracle-jdev-comment:auto-binding-backing-bean-name:backing_view1-->
    </jsp:root>view1.java callMyFunction throws an Exception
        public void callMyFunction(ActionEvent event) throws Exception{
            throw new Exception();
        }view2.jsff is an exception handler
    <?xml version='1.0' encoding='windows-1252'?>
    <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1"
              xmlns:af="http://xmlns.oracle.com/adf/faces/rich">
      <af:activeOutputText value="Exception Occured"
                           binding="#{pageFlowScope.backing_view2.activeOutputText1}"
                           id="activeOutputText1"
                           inlineStyle="font-size:xx-large; color:red;"/>
      <!--oracle-jdev-comment:auto-binding-backing-bean-name:backing_view2-->
    </jsp:root>above taskflow is dragged-drop as a Region in one file main.jspx
    <?xml version='1.0' encoding='windows-1252'?>
    <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1"
              xmlns:f="http://java.sun.com/jsf/core"
              xmlns:h="http://java.sun.com/jsf/html"
              xmlns:af="http://xmlns.oracle.com/adf/faces/rich">
      <jsp:directive.page contentType="text/html;charset=windows-1252"/>
      <f:view>
        <af:document binding="#{pageFlowScope.backing_main.document1}"
                     id="document1">
          <af:form binding="#{pageFlowScope.backing_main.form1}" id="form1">
            <af:region value="#{bindings.taskflowdefinition1.regionModel}"
                       id="taskf1"
                       binding="#{pageFlowScope.backing_main.taskf1}"/>
          </af:form>
        </af:document>
      </f:view>
      <!--oracle-jdev-comment:auto-binding-backing-bean-name:backing_main-->
    </jsp:root>*pressing a commandButton on view1.jsff throws an Exception as expected but does not go to exceptionHandler [view2.jsff]*
    However, this does work with Bounded Task-Flow without page fragments , view1.jspx contains one button, calling one method which throws an Exception,
    view2.jspx is an Exception Handler, and in this case it redirects to the view2.jspx [error page]
    any ideas?
    thanks

    Hi,
    Pretty much. However, you got the event part wrong, which is mostly my fault here. First, let put down some general JSF facts about event handling.
    1. http://java.sun.com/javaee/5/docs/api/javax/faces/component/UIComponent.html#queueEvent(javax.faces.event.FacesEvent)
    2. So, basically, queuing an event on a component means queuing it on its parent until you reach the UIViewRoot that will really actually queue it. That strategy allows iterating components to intercept event queued on their children to record the row index as well so that the data model can be synchronized correctly during the broadcast phase (see http://java.sun.com/javaee/5/docs/api/javax/faces/component/UIData.html#queueEvent(javax.faces.event.FacesEvent) and http://java.sun.com/javaee/5/docs/api/javax/faces/component/UIData.html#broadcast(javax.faces.event.FacesEvent))
    3. Exceptions that aren't handled by the exception handler are thrown during broadcast or various process* methods.
    So, the catch component must leverage these facts to intercept events queued on its children (by overriding queueEvent method) wrapping the original event in a custom on that flag the catch component itself as the source of the event. The result will be that the broadcast method of the catch component will be called to handle the event. The broadcast method must then unwrap the event (to get the original event), gets the original source, then call originalSource.broadcast(originalEvent) within a try-catch block.
    Does it make any more sense put that way? Note that it's an obscure part of JSF so I cannot make it incredibly simple either.
    Regards,
    ~ Simon

  • ABAP Object Exception handling

    Hi all,
    I would very much like some links to learn how to create Exception objects, and how to use them in my ABAP Object apps.
    Thanks in advance!

    hi,
    Object Services classes work exclusively with Class-Based Exceptions. The exception classes are predefined in the system. They always start with CX_OS_.
    Exceptions of the CX_DYNAMIC_CHECK category are passed to the caller using the RAISING clauses of interface methods; class-specific methods of the class actor; attribute access methods of persistent classes; in the transaction object; and the system actors. Such exceptions must be handled here by the user, (in contrast to the general rule that exceptions should be handled within a procedure, not passed along the hierarchy). Thus semantically, the above exceptions of the CX_DYNAMIC_CHECK category belong more to the CX_STATIC_CHECK category. However, they could not be defined as such, due to their incompatibility with existing Object Services applications.
    Check out the link.
    http://help.sap.com/saphelp_erp2005vp/helpdata/en/66/bc7aec43c211d182b30000e829fbfe/frameset.htm
    http://help.sap.com/saphelp_nw04/helpdata/en/fb/35c62bc12711d4b2e80050dadfb92b/content.htm
    http://help.sap.com/saphelp_erp2005vp/helpdata/en/17/f9f44295bae2499e8c56ca4f5106fb/frameset.htm
    Regards,
    Richa.

  • RE: exception handling

    Wayne,
    When an exception occurs, Forte aborts the inner
    most compound statement, after executing the code
    of an exception handler if there is one. If the excep-
    tion is not handled, it still exists after the compound
    statement was aborted, so Forte now aborts the
    remaining inner most compound statement. This
    continues until Forte reaches the root compound
    statement of the tread (or "task" if you will). This
    one will also be aborted and that is the end of the
    thread (task). If you look at the debugger, you will
    see "RIP" in front of this thread. Sure, this thread
    was spawned by another thread. It was started
    by a "start task" call from within some compound
    statement in the parent thread, but this compound
    statement was probably long since closed. Forte
    can't pass the exception on to a higher level com-
    pound statement, because there is none. If the
    thread started with a method that had a return event
    and an exception event, and you started the task
    with "Completion = event" then Forte will post one
    of these events after the root compound statement
    was finished (in other words, the thread was stopped).
    From this event you can see, if the thread wasfinished succesfully or not.
    Of course, an event is not the same kind of thing
    as an exception. You can't raise events, or post
    exceptions.
    So, when an exception is not handled, only the thread
    where this exception occured is cancelled (including
    all it's child threads). The rest of the treads stay alive.
    -----Original Message-----
    From: Wayne Walker [SMTP:[email protected]]
    Sent: Wednesday 22 July 1998 13:49
    To: '[email protected]'
    Subject: exception handling
    I have a problem in handling exceptions detected in a task. I start a
    task
    which performs some function. I also have an event handler which
    recognizes the method_exception returned should an exception be
    detected.
    Once detected by the event handler I force the exception up to
    another
    process which displays the exception to the user. However, it appears
    that
    forte is intercepting the exception before my event handler can detect
    it
    and posts an exception message. Can anyone explain how this mechanism
    works and the best approach for handling exceptions myself vice Forte?
    Thanks,
    Wayne
    To unsubscribe, email '[email protected]' with
    'unsubscribe forte-users' as the body of the message.
    Searchable thread archive
    <URL:http://pinehurst.sageit.com/listarchive/>-
    To unsubscribe, email '[email protected]' with
    'unsubscribe forte-users' as the body of the message.
    Searchable thread archive <URL:http://pinehurst.sageit.com/listarchive/>

    My understanding is that if your client doesn't care (or cannot handle) the exception,
    you throw your exception WRARPPED with EJBException. This way, the container can
    roll back the transaction properly.
    If your client cares (or have the ability to recover) the exception, you should
    define your own exception. They should not be derived from RuntimeException or
    RemoteException or EJBException. If you want to make sure that the transactions
    are rolled back, you call setRollbackOnly() before you throw the exception.
    Charles
    soraya abbasi <[email protected]> wrote:
    I have tried to make my custom exception subclass RemoteException but
    that doesn't work.
    Does that mean to say you can't have custom exceptions thrown to a client?

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

  • MDB Exception handling

    hi,
    I got a simple question about messagedriven beans.
    My MDB is deployed with container managed transaction, attribute "required".
    According to the specification, this causes the transaction to be rolled back if an exception is thrown.
    Will an exception catched within the onMessage method be noticed by the container and handled so that the transaction is rolled back ? I am not sure, thats why I ask. Logically, an exception catched within the onMessage method should not be propagated to the container.
    Can I roll back the message consumption action by calling setrollbackonly() in the catch block of the onMessage method ?
    Best regards, Jubin

    You can make the container roll back the transaction by catching your application specific exception and re-throwing it as an EJBException.
    In session beans you can utilise the SessionContext to setRollBackOnly() but I have never used it in MDBs. Dont see a problem with it though.
    Hope that helps.

  • 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

Maybe you are looking for

  • Implementing Webservices Doubt

    Hi, i have few queries in my mind we have to integrate Third party webservices with our SAP R/3 1) Assume that in IDOC--- SOAP scenario( External Web Service)  who has to generate the WSDL file???? 2) In SOAP - IDOC scenario( External web service) wh

  • Find next open number

    In SAP R/3 you can, when creating an object, let the system "find the next open number" or "find number after last assigned". Is it possible to make this function in MDM? When creating a record I suspect an suggestion for the value of one of the fiel

  • HUGE issues with I Pod Touch and new software

    Christmas Day I opened I tunes to load some new CD's for my hubby and I. It said I needed the new I Tunes, so I downloaded it. Procedeed to get CD's loaded and plugged in hubby's I pod (it's about 6 years old and wheel style) it synced and was done i

  • Formating in Disk Utilility (Leopard Version)

    Fix request for bug in Disk Utility. I was formating a USB Drive (previously formated as OSX Journaled) into Dos format and it said that it had formated properly, however Windows XP could not recognise the drive. I Formated it again and this time not

  • A email address i use has started to return messages from the destination server as undeliverabler

    tb 35.1 windows 7 problem suddenly started