Handling socket exception - Retrying a "try" block

I have a program which attempts to retrieve an object through a socket. However sometimes I get the following exception:
java.net.SocketException: Connection reset
This is a problem as I need the object to continue program execution.
An overview of the code is:
try {
            UrlServerObject crawlUrlObj = getUrlToCrawl();
            // Download webpage at the url returned by getUrlToCrawl()
            webpage = loadPage(crawlUrlObj);
catch(java.net.SocketException ex) {
          System.err.println("An exception occurred.\n" +
                    "The exception was: " + ex.toString());
        }The getUrlToCrawl() method simply opens a socket a communicates with a server which sends back an object.
My question is what is the best way to catch the exception and "retry" the complete "try" block until an object is read?
Thanks

When you say a loop, do you mean something along the
lines of:
boolean gotUrl = false;
while(!gotUrl) {
UrlServerObject crawlUrlObj = getUrlToCrawl();
if(crawlUrlObj != null) gotUrl = true;
}The exception would be thrown in the catch block
still though?getUrlToCrawl is presumably the code you originally posted? Yep, that's about the size of it. Although I wouldn't keep trying until you got a URL, you should consider the possibility that there isn't one, and deal with that. I'd try it a set number of times, and move on after that

Similar Messages

  • Handling loop exception in an anonymous block

    hI ,
    I have a an anonymous block
    declare
    cursor
    local variables
    begin
    open cursor
    some statements
    loop
    some statement ;
    some othet statement;
    select something from sometablein local variable where some field = cursor.value ;
    some more statements
    end loop
    some more statements
    exception
    when whatever
    then whatever
    end;
    Now my select statement may give a NO_DATA_FOUND error which i want to catch and ignore .
    Pls tell me how to do it.

    So that mean you can have multiple exception blocks
    in a pl/sql script ?You can have one exception handler per execution block.
    Execution blocks can be nested inside other execution blocks.
    Handling the error within one exception handler causes execution to return out to the execution of the parent block.
    Raising an error within one exception handler causes the execution to go straight to the exception handler of the parent block.
    e.g.
    -- execution block 1
    BEGIN
      -- execution block 2
      DECLARE
        myvar number;
      BEGIN
        SELECT mynumber INTO myvar FROM mytable;
      EXCEPTION
        WHEN NO_DATA_FOUND THEN
          NULL;  -- handle error and return execution to block 1
        WHEN OTHERS THEN
          RAISE; -- raise any other errors to block 1 exception handler
      END; -- block 2
      DBMS_OUTPUT.PUT_LINE('Select took place successfully or no data was found');
    EXCEPTION
      WHEN OTHERS THEN
        DBMS_OUTPUT.PUT_LINE('An error occurred either in block1 or in block 2 (except for NO_DATA_FOUND in block2)');
    END;

  • Handling ABAP Exceptions in a Block

    Hi,
    If a background task calls an ABAP Class Method and that method throws a defined exception of type CX_BO_ERROR, I would expect to see a possible outcome for that exception that would allow me to handle the exception for the specific task. If I activate that outcome then an exception handling path will be displayed on the graphical representation which is taken if the exception is then raised by the method. If the outcome is disabled then the workitem goes to error.
    If I want to catch these exceptions (for multiple tasks) in an enclosing block in order to handle them in a single, standard way, how do I achieve that? It does not seem possible to simply define the exception type in the enclosing block and then activate it in order to then be able to automatically catch any exceptions of a particular type that have their outcomes disabled in their individual tasks. It would appear that I have to activate the outcomes for each task and then raise it during with a Process Control item on the exception handling path of the task. This seems to defeat the object of having exception handling at the Block level. Is my understanding correct or am I doing something wrong?
    Also, is it possible to capture the class exception object from the method call and store it in the Task Container (in order to get text & longtext details)?

    Thankyou for both of your responses.
    I understand that an individual ABAP Object or BOR method (call during an Activity) can raise an exception which can be handled as a separate outcome of that activity. However, if there are multiple Activity steps in the workfow that can all throw similar exceptions and I want to react to all of those exceptions in a uniform way, it seems excessive to have to handle each exception individually for each Activity in order to do the same thing (e.g. I may just want to send a standard email to someone or trigger another workflow event).
    I may have misunderstood things but I thought that the purpose of the Block step was to be used as a kind of TRY..CATCH mechanism that will allow exceptions to thrown to the Block by enclosed Activities without the need for enabling outcomes at the Activity level. I thought it would be possible for the exception type to be defined in the Block properties so that all exceptions of that type could be handled at a higher level by a single Block outcome (regardless of which enclosed Activity threw it). If this is the case then I do not see the point in having to define individual outcomes for each activity within the Block.
    That said, I cannot seem to get it to work without enabling the outcome for each activity and using a Process Control step to raise the exception to the Block (which seems to defeat the object because I have, in fact, just handled the exception!). The reason for my original posting is to verify whether or not what I am trying to do is possible and to find out what I doing wrong with regards to Block configuration.
    Kind Regards
    Simon.

  • Oracle JSP Exception code too large for try block

    My jsp is exceeding the memory limit (64KB for Oracle 10g App server i think its the JVM limit),
    so it is throwing exception ,code too large for try block,how to over come this,I cant minimize the use of logic tags because it is business requirement.please help me out.

    I think you need to give a value to the attribute buffer in the <%@ page%> directive to solve the problem.
    There will not be any need of going for pagination then.
    buffer="none | 8kb | sizekb"The buffer size in kilobytes used by the out object to handle output sent from the compiled JSP page to the client Web browser. The default value is 8kb. If you specify a buffer size, the output is buffered with at least the size you specified.
    check the documentation at
    http://java.sun.com/products/jsp/tags/11/syntaxref11.fm7.html
    Uday

  • Can't throw exception inside try block!

    Hi,
    I'm having a problem trying to throw an error inside a try block.
    To illustrate:
    public class TestException {
    public TestException() {
    try {
    int ret = foo();
    System.out.println("ret is " + ret);
    } catch (Exception ex) {
    System.out.println("exception caught");
    public int foo() throws Exception {
    int ret = 0;
    try {
    throw new Exception("test exception");
    } finally {
    return ret;
    public static void main(String[] args) {
    new TestException();
    If I run this the only output is "ret is 0" - I do not catch the thrown exception! What am I doing wrong?
    Any and all help will be very gratefully received.
    Thanks.

    I need to correct myself: I've re-read the spec, and actually the behaviour is conformant with the JLS: JLS says that the return statement completes abruptly, and an abrupt return in a finally block that didn't have a (applicable or any) catch block will result in the original exception being 'forgotten'.
    Very unintuitive, but as-spec'ed

  • Handling the ASSIGN_TYPE_CONFLICT in a try catch block

    Hi,
    Post WAS 610 all system exceptions are handled by exception classes, I could not find the exception class for the runtime exception ASSIGN_TYPE_CONFLICT, if any body is in knowledge of the same or knows of a better way to handle the runtime exception kindly let me know.
    Thanks in advance.
    Aniruddha Gargya

    Hi Raja,
    I have already tried all teh exceptions listed for type conversion and assign. The help document also suggested that teh exception class name for a runtime exception will appear in the system trace.
    The issue still remains where it was, When i get this execption from a web page the same is not being caught.
    Thanks and Regards,
    Aniruddha Gargya

  • Won't recognise code in try block

    I've got a try block which has a line of code in it as shown:
         public static String ProcessUserInput(){          
              BufferedReader kbd = new BufferedReader(new InputStreamReader(System.in));
              try{
         String line = kbd.readLine();
    catch (IOException ex)
    System.out.println( "Error reading keyboard input." );
    return line;
    When i compile this it gives me this error:
    cannot resolve symbol
    symbol : variable line
    location: class UserException
    return line;
    It seem like it does not recognise what is in the try block why is this.

    A variable's scope--the piece of your code where it's visible--is the nearest enclosing block. In this case, line is only visible in the try block.
    String line = null;
    try {
        line = kbe.readLine();
    catch (...) {
    return line;Side note: Just printing an error message is NOT the way to handle exceptions. First, it lets subsequent code continue executing as if everything's fine--you've taken away its way of knowing that things are NOT fine. You should either actually handle the exception (by providing some default behavior, or retrying), or else just let it be thrown, or wrap it and rethrow it.

  • Try block inside a try block - who is throwing StaleConnectionException?

    int retry = 0;
    try{ //MAIN TRY
    //GET Datasource from context<---is this throwing?
    boolean retry = false;
    do {
         try {
              retry = false;
    GET CONNECTION FROM DATASOURCE<--or shld this be?
         }catch(SQLException e) {
         //FIRST CATCH
         if (retryattempts++ < 3){
              retry = true;
    } while (retry);
    //DO something which requires try block
    }catch(SQLException e)
    {//Second catch
    When I do this the StaleConnectionException is caught by the second catch... does this mean that the staleconnectionexception is thrown when getting datasource from initialcontext and not while getting connections?
    Edited by: wannaBeACsGrad on Jan 10, 2008 9:09 AM

    I am not sure what your are trying to do. Your code as posted is incomplete and could not possibly compile. The Try/catches do not seem to be nested.
    More importantly, why in the world would you ever want to have a try inside a try? You can have a single try, then several different calls in loops or whatever that can potentially throw Exceptions and then have mulitple catch statements to handle them. For instance, you could have something like this:
    try {
    } catch (NullPointerException ne) {
       // handle null issues here
    } catch (NumberFormatException nfe) {
       // handle number format issues here
    } catch (Exception e) {
       // everything else falls here
    }Keep in mind that you don't want to do any "Error Hiding". Make sure you handle each case appropriately.

  • How can my custom DCErrorHandler class throw/handle an exception?

    I had written a custom DCErrorHandler extending the DCErrorhandlerImpl as similar as shown in SRDemo example.
    Assume that i have a method authenticateUser() in AppmoduleService Class calling from Backing Bean.java where in i encountered ArrayOutOfBoundsException. So how can i catch this exception without using try catch block? if i use
    try{
    authenticateUser();
    catch(Exception eX)
    {} the exception is well-handled.Then what exactly my customErrorHandler class doing?
    Do the above customErrorHandler class help in this case by replacing try-catch?

    From where my customErrorHandler's methods are invoked.
    If i want to do it exlicitly from any method of my backing bean class can i do it?
    LoginBackingBean.java
    public String loginButton_Action()
    ArrayList userDetailsList = null;
    LoginService service = (LoginService)ADFUtils.getLoginServiceInterface();
    if(service != null)
    userDetailsList = service.checkUserLoginDetails(getUsername(), getPassword());
    if(userDetailsList != null && userDetailsList.size()>0) {                 
    JSFUtils.storeOnSession("key_loggedUserDetails",userDetailsList);
    return "success";
    else
    JSFUtils.addFacesErrorMessage("You have entered an invalid User name and/or Password.");
    return "wrongLogin";
    else{
    return "wrongLogin";
    Now assume that i have customDCErrorHandler class and also assume that an exception will be thrown ..say ArrayOutOfBoundException.
    if i keep the above code in try and catch block the user login screen is remained as it is by catching the exception.
    if i remove the try and catch block user screen if filled up with so many debugging messages as shown : "500 Internal Server Error
    javax.faces.FacesException: #{login.loginButton_Action}: javax.faces.el.EvaluationException: java.lang.IndexOutOfBoundsException: Index: 1, Size: 0     at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:98)     at oracle.adf.view.faces.component.UIXCommand.broadcast(UIXCommand.java:211)     at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:287)     at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:401)     at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:95)     at com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:245)     at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:110)     at javax.faces.webapp.FacesServlet.service(FacesServlet.java:213)
    So can we avoid this by using my customDCErrorHandler ???? If so i need a sample code.
    More over if i use a customDCErrorHandler class,
    Do i need to bother about the exceptions occuring in the application?

  • How to handle XScript Exceptions ?? HELP !!

    hey buddies !!!
    I am getting the following exception in the browser for some jsp that is using XSCript.
    "Caught exception when evaluating expression "MIDC PHASE II DOMBIVALI {E}" with available binding contexts [actionForm, pageFlow, globalApp, request, session, appication, pageContext, bundle, container, url, pageInput]. Root cause: com.bea.wlw.netui.script.xscript.IllegalContextStateException: The context "E" could not be found. "
    Its okay that i am gettign this exception but i want to to know how to handle this exception. I tried using a try catch block but it didnot catch the exception and it still showed on the screen. I want to know how to handle this exception in the jsp ...
    Please help me ...thanks a lot !!!
    Nikhiol

    Nikhil--
    Can you paste in the tag (with the attributes) that is throwing the expression?
    Are you trying to data bind to "{E}"? If so, that's not a supported NetUI data binding context
    and the exception is legit. There isn't really a way to "handle" it -- it's more of a runtime error
    that occurs during regular development. When the application is deployed, such exceptions shouldn't
    occur.
    <g>
    Eddie
    Nikhil Gonsalves wrote:
    hey buddies !!!
    I am getting the following exception in the browser for some jsp that is using XSCript.
    "Caught exception when evaluating expression "MIDC PHASE II DOMBIVALI {E}" with available binding contexts [actionForm, pageFlow, globalApp, request, session, appication, pageContext, bundle, container, url, pageInput]. Root cause: com.bea.wlw.netui.script.xscript.IllegalContextStateException: The context "E" could not be found. "
    Its okay that i am gettign this exception but i want to to know how to handle this exception. I tried using a try catch block but it didnot catch the exception and it still showed on the screen. I want to know how to handle this exception in the jsp ...
    Please help me ...thanks a lot !!!
    Nikhiol

  • Throwing or handling the exception.

    Hi,
    Which is the good idea.
    *1 .* throwing the exception to the caller method.
    *2 .* handle the exception at the save place.(with the help of try/catch).
    Any pointer will be highly appreciated.
    Regards,
    Alok

    Usually #1, though sometimes you'll wrap it in an exception more appropriate for that layer.
    To handle the exception, you have to truly handle it.You have to provide a correction for whatever went wrong. That might mean retrying or using some default value or calling some other "safe" algorithm. If you can't actually fix it, you have to throw something to let the caller know what went wrong. It's then up to him to determine whether to handle it or throw it to his caller.

  • Is there a way to handle system exception ERROR_MESSAGE?

    Hi,
    I have a program executed in background, which produces a bunch of consecutive documents for a set of Bulk Shipments -> TD Loading and TD Delivery Confirmation. To create those documents I use function modules 'OIGI_LOADING_CREATE' and 'OIGI_DEL_CONF_CREATE'  - both from Industry-Solution Oil-and_Gas (IS-Oil).
    In some cases these FM-s produces error messages (E-type) which cancel execution of the program and broke my flow-logic.
    Below are few messages recorded in a job log for my task:
    18.08.2005 15:56:41 Job started                                                                         
    18.08.2005 15:56:41 Step 001 started (program /PTRL/TAS_POSTPONDED_SYNC, variant , user name IMUTAFCHIEV)
    18.08.2005 15:56:58 Shipment 180753 saved                                                               
    18.08.2005 15:57:06 The plant data of the material 177 is locked by the user BMINKOV                    
    18.08.2005 15:57:06 The plant data of the material 177 is locked by the user BMINKOV                    
    18.08.2005 15:57:06 The plant data of the material 177 is locked by the user BMINKOV                    
    18.08.2005 15:57:06 Job cancelled after system exception ERROR_MESSAGE                                  
    Both function modules are not designed to handle any exceptions, and in owr environment (4.6c) there is no documented system exception 'ERROR_MESSAGE' which to be handled in CATCH-ENDCATCH block.
    Is there a way to handle this exception and to track the list of error messages produced by some FM into an internal table, log, whatever, as it is done in the log of the background job. I need to find a way write these messages in my log-tables and to proceed further with my flow-logic.
    FYI: my program executes an RFC call to a remote system and retrieve a list of documents which need to be synchronized with R/3. I loose information, if the R/3 broke my flow-logic.
    Any help would be highly appresiated.
    Many thanks in advance.
    Ivaylo Mutafchiev

    Sven,
    I made few programs where we used business scenario:
    IS-Oil Shipment => IS-Oil Loading Confirmation => IS-Oil Delivery Confirmation.
    All of them are based on Function Module call:
    1. OIGI_LOADING_CREATE and
    2. OIGI_DEL_CONF_CREATE.
    To load shipment I call 1st FM in a way:
      CALL FUNCTION 'OIGI_LOADING_CREATE' DESTINATION 'NONE'
           EXPORTING
                I_SUBRC     = 9  "save and commit
                I_SHNUMBER  = shNumber
                I_VEHICLE   = vehicle
                I_LDPLT     = plant
                I_LDDATE    = loadDate
                I_LDTIME    = loadTime
                I_LDCDAT    = loadDate
                I_VEH_NR    = veh_nr
           TABLES
                T_OIGISVMQ  = quantity_items
                T_OIGISVMQ2 = hpm_append
                T_OIGISIQ   = doc_quan_items
           EXCEPTIONS
                COMMUNICATION_FAILURE = 1 MESSAGE p_error
                SYSTEM_FAILURE = 2 MESSAGE p_error.
    To confirm shipment (status 4) I call the same FM with:
      CALL FUNCTION 'OIGI_LOADING_CREATE' DESTINATION 'NONE'
           EXPORTING
                I_SUBRC    = 39  "confirm & commit 2nd step
                I_SHNUMBER = shNumber
                I_VEHICLE  = vehicle
                I_LDPLT    = werks
           EXCEPTIONS
                COMMUNICATION_FAILURE = 1 MESSAGE sh_error
                SYSTEM_FAILURE = 2 MESSAGE sh_error.
    And finaly to finish process (status = 6) I call 2nd FM in a way:
      CALL FUNCTION 'OIGI_DEL_CONF_CREATE' DESTINATION 'NONE'
           EXPORTING
                I_SUBRC         = 19  "save, confirm and commit
                I_SHNUMBER      = shNumber
                I_RAPID_CONFIRM = 'X'
                I_DDCDAT        = loadDate
                I_DLDATE        = loadDate
                I_DLTIME        = loadTime
           EXCEPTIONS
                COMMUNICATION_FAILURE = 1 MESSAGE p_error
                SYSTEM_FAILURE = 2 MESSAGE p_error.
    FYI: It tooks me some time to 'investigate' and find correct use of these function modules. And I worked VERY CLOSE with our SD consultant.
    For details (what the export parameters and tables consist of) and sample code, please contact me at:
    ivaylo dot mutafchiev at vbs dot bg
    I would be glad to share my knowlege.
    Regards,
    Ivaylo

  • Hi, exception branch of a block

    If I define a exception branch for a block such as DB error. Do I need to send DB error message to the Integration process to stop it when error occurs?
    I'm not sure about how the exception here works.
    Thanks, guys.

    Hey,
    I'm not sure about how the exception here works
    Nice thread on BPM exception handling..
    check this..
    Re: Exception Handling
    Thanks,
    Vijaya

  • Is it possible to get back to the Try block from a Catch block?

    I would like to perform validations on a config file. To do so, I have a method which will throw a MissingConfigException or an InvalidConfigException if something is missing or if something doesn't match a regex pattern. Although I have to do that with many different configs and I would like to go through all of them so that my error message will report all missing / incorrect configs at once instead of 1 at a time. Thus, I wanted to know if there would be any way I could do something like:
    try {
         config.validate("ServerPort","\\d+");
         config.validate("MaxClients","\\d+");
    } catch(MissingConfigException e) {
    } catch(InvalidConfigException e) {
    and have the catch block executed before going through the try block from where the exception was thrown.
    Thanks in advance!                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    No, you can't jump back into the try. You can put your try/catch inside a loop though, so that if one fails, it will loop around and start a new try for the next one. Define a class that holds all the data you need to pass to validate, and make an array or List of those objects. Change or add a validate signature that takes this object, or just extract the strings from each one when you call validate.
    ThingToValidate[] val = new ThingToValidate[] { new ThingToValidate("ServerPort", "\\d+"),
        new ThingToValidate("MaxClients", "\\d+"),
    for (int ix = 0; ix < val.length; ix++) {
        try {
            config.validate(val[ix]);
            // OR
            config.validate(val[ix].getThingy, val[ix].getOtherThingy[]);
        catch (....) {
            // logger.warn("failed...");

  • How to handle multiple exceptions by the same code?

    Hi, all:
    In my situation I want AException and BException handled by the same code, while CException and DException handled by another code. How can I write my try-catch code in a simple way? Of course I can do the following:
    public void TheMainFunction() {
        try {
        } catch (AException e) {
            Handle_AB();
        } catch (BException e) {
            Handle_AB();
        } catch (CException e) {
            Handle_CD();
        } catch (DException e) {
            Handle_CD();
    private void Handle_AB() {
    private void Handle_CD() {
    }But is there a simpler way?
    Thanks in advance.

    If you have one or two places in your code that need multiple exceptions, just do it with multiple catch statements. Unless you are trying to write the most compact Programming 101 homework program, inventing tricks to remove two lines of code is not good use of your time.
    If you have multiple catches all over your code it could be a code smell. You may have too much stuff happening inside one try statement. It becomes hard to know what method call throws one of those exceptions, and you end up handling an exception from some else piece of code than what you intended. E.g. you mention NumberFormatException -- only process one user input inside that try/catch so it is easy to see what error message is given if that particular input is gunk. The next step of processing goes inside its own try/catch.
    In my case, the ArrayIndexOutOfBoundsException and
    NumberFormatException should be handled by the same way.Why?
    I don't think I have ever seen an ArrayIndexOutOfBoundsException that didn't indicate a bug in the code. Instead of an AIOOBE perhaps there should be an if statement somewhere that prevents it, or the algorithm logic should prevent it automatically.

Maybe you are looking for

  • How can I share contacts in a specific group

    I want to share a specific group of contacts without having to share each of the contacts individually.

  • False colours in Photoshop Elements 5.0 and Lightroom (trial)

    Both these applications seem unable to display certain dark colours. Areas that appear a subtle dark brown or grey in other apps (Windows Picture and Fax viewer, Windows Photo Editor, Picasa) appear in Adobe as a restricted range of dark green, blue

  • Problem with purchased

    I have a problem with adding gems in app " clash of clans " . It is not adding after purchased

  • How to quit an AppleScript programmatically?

    I have an applescript that is continually running. Every 60 seconds it opens an application which runs certain processes. My Problem is that while the applescript is running the computer is not able to restart or shutdown. So I need to capture the sh

  • Can't open packets in Wireshark from Cisco IME. Please Help.

    Hello, I am using the Cisco IME with a 4240 IPS.  I am unable to "trigger" packet or open any of the packets in wireshark when I'm looking at an event.  The little Wireshark button on the bottom right corner is just grayed out.  Can anyone possibly h