0

Can a catch block in java simply re-execute the main block of code altogether?

I have a program that iterates every 5 minutes and looks at a plaintext file. If there have been changes, it executes a try block of code which involves converting the file to html and ftping it to a website. It runs flawlessly with the exception of random IO interruptions and the such. Is there any way to simply tell it that if it encounters said exception, just go ahead and throw everything out the window and start from the main block of code again? Alternatively, is there a simple way to get this to run as a service that isn't going to stop executing because of the same problems?

import java.io.*;
import java.util.*;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import java.sql.Timestamp;

public class PrintOutConvosFtp4
{
public static void main(String[] args) throws IOException, InterruptedException
    {
    boolean infiniteLoop = true;
    long currentLoopModified = 0;
    long lastLoopModified = 0;

    while (infiniteLoop)
    {
    currentLoopModified = new File("C:/Documents and Settings/Cuckoo/Desktop/Syss-convos.LOG").lastModified();
    if (currentLoopModified > lastLoopModified)
    {

    //Read in the conversation log
BufferedReader reader = new BufferedReader(new FileReader("C:/Documents and Settings/Cuckoo/Desktop/Syss-convos.LOG"));
FileWriter output = new FileWriter("C:/Documents and Settings/Cuckoo/Desktop/Conversations.html");
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = reader.readLine()) != null)
    //Remove some unnecessary clutter from the log
 {
 if (!(line.contains("just hung up!!!") || line.contains("just left the Realm.")
        || line.contains("Hurry, I've many esoteric secrets to divulge, and welcome to BaDbOy's realm.")
        || line.contains("For custom MegaMud paths and additional information, check out the website:")
        || line.contains("Syss gossips: Discuss new ideas/issues & see the most up to date information on Facebook!")
        || line.contains("Syss gossips: http://www.facebook.com/groups/EsotericEdits/")
        || line.contains("Syss gossips: MME Dats, Megamud path files and quest walkthroughs are available at my site")
        || line.contains("Syss gossips: www.esoteric-edits.fhero.net")
        || line.contains("telepaths: @")
        || line.contains("I'm a bot.  Try telepathing me with @commands.")
        || line.contains("Syss gossips: Remember, you can telepath me @commands for useful things like adding lives.")
        || line.contains("Syss gossips: Bring a friend, help keep mud alive!")
        || line.contains("You say \"http://esoteric-edits.fhero.net/\"")
        || line.contains("For a list of available commands, you can telepath me with @commands.")))
 {
 //Make the dates american style
     String day = line.substring(0,2);
     String month = line.substring(3,5);
lines.add(month + "/" + day + line.substring(5));
}


 }
//initialize the output file with HTML header
output.write("<html>");
output.write(System.getProperty("line.separator") + "\t<head>");
output.write(System.getProperty("line.separator") + "\t\t<link type=\"text/css\" rel=\"stylesheet\" href=\"stylesheet.css\"/>");
output.write(System.getProperty("line.separator") + "\t\t<title>Esoteric Edits BBS - Conversation Log</title>");
output.write(System.getProperty("line.separator") + "\t</head>");
output.write(System.getProperty("line.separator") + "\t<body>"+ System.getProperty("line.separator") + System.getProperty("line.separator"));
output.write(System.getProperty("line.separator") + "<div id='cssmenu'>");
output.write(System.getProperty("line.separator") + "\t\t<center><img src=\"logo_10_2.png\">");
output.write(System.getProperty("line.separator") + "<ul>");
output.write(System.getProperty("line.separator") + "\t<li> <a href='index.html'><span>Home</span></a></li>");
output.write(System.getProperty("line.separator") + "\t<li> <a href='downloads.html'><span>Downloads</span></a></li>");
output.write(System.getProperty("line.separator") + "\t<li> <a href='Quests.html'><span>Quest Walkthroughs</span></a></li>");
output.write(System.getProperty("line.separator") + "\t<li> <a href='https://www.facebook.com/groups/EsotericEdits/'><span>Facebook</span></a></li>");
output.write(System.getProperty("line.separator") + "\t<li> <a href='captures.html'><span>Captures</span></a></li>");
output.write(System.getProperty("line.separator") + "\t<li class='last'> <a href='FAQs.html'><span>FAQs</span></a></li>");
output.write(System.getProperty("line.separator") + "</ul></center>");
output.write(System.getProperty("line.separator") + "</div><div id='mainpage'>");
output.write(System.getProperty("line.separator") + "<center><img src=\"divider.png\"></center>");

//write out a new file with HTML coloration
for (ListIterator<String> iter = lines.listIterator(); iter.hasNext(); ) 
{
    String currentline = iter.next();
    output.write("<b>"); //make everything bold
    if (currentline.contains("gangpaths: "))
{
output.write(System.getProperty("line.separator") + "<font color=\"#808000\">" + currentline + "<br></font>");
}
    else if (currentline.contains("gossips: ") || currentline.contains("auctions: "))
{
output.write(System.getProperty("line.separator") + "<font color=\"#FF00FF\">" + currentline + "<br></font>");
}
else if (currentline.contains("Broadcast from "))
{
output.write(System.getProperty("line.separator") + "<font color=\"yellow\">" + currentline + "<br></font>");
}
else if (currentline.contains("says \"") || currentline.contains("greets you.") || currentline.contains("bows deeply.")
             || currentline.contains("breaks into a wide grin.") || currentline.contains("You say \"") 
             || currentline.contains("nods affirmatively.") || currentline.contains("grin slyly"))
{
output.write(System.getProperty("line.separator") + "<font color=\"green\">" + currentline + "<br></font>");
}
else
{
output.write(System.getProperty("line.separator") + currentline + "<br>");
}
}
//finalize the HTML footer
output.write(System.getProperty("line.separator") + "</b>");
output.write(System.getProperty("line.separator") + "</div>");
output.write(System.getProperty("line.separator") + "</body>");
output.write(System.getProperty("line.separator") + "\t</html>");
output.close(); //file is finalized locally



//define variables for FTP process
String server = "servername";
int port = 21;
String user = "fake";
String pass = "password";

//begin FTP process to web server
FTPClient ftpClient = new FTPClient();
FileInputStream fis = null;
try {

    File localFile = new File("C:/Documents and Settings/Cuckoo/Desktop/Conversations.html");
    ftpClient.connect(server, port);
    ftpClient.login(user, pass);
    ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
    fis = new FileInputStream(localFile);
    String remoteFile = "/public_html/Conversations.html";
    ftpClient.storeFile(remoteFile, fis);
    java.util.Date currentDate = new java.util.Date();
    Timestamp ftpTimestamp = new Timestamp(currentDate.getTime());
    //Create writer file to log iterations of the loop as successful or skipped.
    Writer writer = new BufferedWriter(new FileWriter("C:/Documents and Settings/Cuckoo/Desktop/Convo-Upload.log", true));
    writer.append("Successfully uploaded file as of " + ftpTimestamp.toString() + System.getProperty("line.separator"));
    writer.close(); 
    ftpClient.logout();
} catch (IOException e) {
    //turn the stack trace into a string and output to the log file
    StackTraceElement[] stack = e.getStackTrace();
    String theTrace = "";
    for(StackTraceElement IOstackline : stack)
    {
       theTrace += IOstackline.toString();
    }
    Writer writer = new BufferedWriter(new FileWriter("C:/Documents and Settings/Cuckoo/Desktop/Convo-Upload.log", true));
    writer.append(theTrace + System.getProperty("line.separator"));
    writer.close(); 
} finally {
    try {
        if (fis != null) {
            fis.close();
        }
        ftpClient.disconnect();
    } catch (IOException e) {
        //turn the stack trace into a string and output to the log file
        StackTraceElement[] stack = e.getStackTrace();
        String theTrace = "";
        for(StackTraceElement IOstackline : stack)
        {
           theTrace += IOstackline.toString();
        }
        Writer writer = new BufferedWriter(new FileWriter("C:/Documents and Settings/Cuckoo/Desktop/Convo-Upload.log", true));
        writer.append(theTrace + System.getProperty("line.separator"));
        writer.close();
        e.printStackTrace();
        }
    }


lastLoopModified = currentLoopModified; //set the timestamp for the lastmodified on the file being read in

}
    else
    {
        java.util.Date currDate = new java.util.Date();
        Timestamp currTimestamp = new Timestamp(currDate.getTime());
        //Create writer file to log iterations of the loop as successful or skipped.
        Writer writer = new BufferedWriter(new FileWriter("C:/Documents and Settings/Cuckoo/Desktop/Convo-Upload.log", true));
        writer.append("Did not detect any new content in file.  Did not upload as of " + currTimestamp.toString() + System.getProperty("line.separator"));
        writer.close(); 
    }
    Thread.sleep(300000); //5 minutes
}

}
}
cuckoo
  • 67
  • 8
  • 3
    Post your code. Because the only answer I can give at the moment is *probably*. – Elliott Frisch Jul 23 '14 at 03:51
  • Catch the exception and log the error then let the loop continue (i.e. don't re-throw or throw the exception). Of course better answers will be had with actual code examples. – RossBille Jul 23 '14 at 03:55
  • Posted sample code. Sorry, I thought this would be a relative straight forward "yes or no" as far as how exceptions were handled. I guess the name itself should've been an indicator.... – cuckoo Jul 23 '14 at 03:58
  • Well why do you stuff all your code in main, construct a separate function and declare throws exception from there, try-catch it in main where you call the function, that way you can easily recall the function whenever you want rather than executing main again. – Mustafa sabir Jul 23 '14 at 04:00
  • @cuckoo - `FTPClient cannot be resolved to a type` Btw, what is your code doing ? – Erran Morad Jul 23 '14 at 04:03
  • This is the first java I've written from scratch in several years. It started as a simple "convert this file", turned into "let's see if we can ftp it" to "lets see if we can automate it"... so the code started very basic and I have not taken the time to split it into methods at this point, especially until I have an understanding of whether or not doing so is worthwhile -- i.e. can I make this program run more stable without having to restart it all the time – cuckoo Jul 23 '14 at 04:03
  • Borat -- In order to use FTPClient you need to have the apache commons package installed in your libraries. I described the overall layout of my program in the block prior to the code. – cuckoo Jul 23 '14 at 04:04
  • @cuckoo See this [post](http://stackoverflow.com/questions/2258066/java-run-a-function-after-a-specific-number-of-seconds), you can keep calling your function after specific interval of time, saving you the manual restart headache – Mustafa sabir Jul 23 '14 at 04:07

2 Answers2

0

Update :

Simply just catch all the exception, then it will be fine

For example :

  public static void main(String[] args) throws Exception {
    while (true) {
      try {
        doAll();
      } catch (Exception e) {
        e.printStackTrace();
      }
      Thread.sleep(5000);
    }
  }

  public static void doAll() {
    doA();
    doB();
    doC();
  }

  public static void doA() {
    System.out.println("Do A");
  }

  public static void doB() {
    System.out.println("Do B");
  }

  public static void doC() {
    System.out.println("Do C");
    throw new RuntimeException();
  }
Rangi Lin
  • 9,303
  • 6
  • 45
  • 71
  • Thank you for providing the simple answer I was expecting/looking for prior to posting my code in the first place. I will mark this as an answer once I have time to update my code accordingly and verify it does indeed function :) – cuckoo Jul 23 '14 at 04:06
  • 1
    This is wrong. If each time you run `doAll()` an exception is thrown (i.e. due to some external condition that is not being cleared) you will eventually get `StackOverflowException`. – Jim Garrison Jul 23 '14 at 04:10
  • This will cause a new level to be pushed on the call stack for each exception, causing stack overflow if there are too many. – Patricia Shanahan Jul 23 '14 at 04:10
  • This is a overly simplified example, as I said "Remember to make sure it won't become a infinite loop." – Rangi Lin Jul 23 '14 at 04:15
  • I tried following this format and it seemed like it just wanted me to add throws IOEXception and InterruptedException onto my main method, which makes me think that it's just going to bomb out in main again anyways. Also the concerns about the stack overflow-- what would be necessary to clear out in order to avoid that? is there a simple way to write a clearJunk() method to re-initialize everything? – cuckoo Jul 23 '14 at 04:21
  • I didn't realize you are trying to rerun every few second, let me change my answer – Rangi Lin Jul 23 '14 at 04:35
  • @Rangi Lin -- If you see the comment thread on the other proposed answer, I think the try/catch may not have even been the reason for my program exiting, and so I think this is a non-issue, though I very much appreciate your time and effort. – cuckoo Jul 23 '14 at 04:43
  • @JimGarrison why would you get a StackOverflowException? There is no recursion involved. There are other problems though, because this loop never terminates, even if no exception is thrown. The line after `doAll();` should read: `break;` – Erwin Bolwidt Jul 23 '14 at 04:48
  • 1
    @ErwinBolwidt The answer has changed significantly since I posted the comment; the original recursion has been removed. – Jim Garrison Jul 23 '14 at 16:09
0

Untested code:

  public void run() {
    while(true) {
      initialize();
      try {
        doCommunication();
      } catch (WhateverException e){
        logIt(e);
      }
    }
  }

The idea is to stay in the while-loop, re-running the initialization each time there is an exception.

Patricia Shanahan
  • 25,849
  • 4
  • 38
  • 75
  • I'm not sure I follow what is happening here, or rather supposed to be happening. At what point is the loop being restarted? Does initialize() hold special rights in java? Forgive the noob questions – cuckoo Jul 23 '14 at 04:25
  • The loop restarts on completion of the try-catch - it is not returning, calling System.exit(), or rethrowing the exception, just logging it. I just meant to suggest that if there is any set-up you need to do, and redo after an exception, you put it in a method called initialize(). – Patricia Shanahan Jul 23 '14 at 04:28
  • Ahh okay, well the issue I ran into was that I just had my program running in my Eclipse environment for about a day and a half. One error showed in the log, but the program seemed to keep running. However, the log seemingly stopped running at some point during today, so I thought perhaps one of the exceptions caused it to exit. Currently the catch blocks in my code are doing nothing but printing the exceptions out. Does this mean that my code stopping execution was probably just a timeout from my Eclipse environment, and perhaps had nothing to do with the stack trace errors? – cuckoo Jul 23 '14 at 04:31
  • That is a different question, and would definitely have to be treated as a debug-type question, requiring a lot more information about your code. – Patricia Shanahan Jul 23 '14 at 04:33
  • I suppose what I am asking more specifically is (if you know), does throwing an exception (via a try/catch block) automatically imply that the code is going to stop executing? If you would prefer, I can post these as new questions. – cuckoo Jul 23 '14 at 04:35
  • A try-catch block is to do with catching exceptions, not throwing them. You can have code that runs indefinitely despite exceptions. – Patricia Shanahan Jul 23 '14 at 04:37
  • Thank you. I think this entire thread was a huge misunderstanding on my part of how try/catch works. I will try to find alternative ways to execute my java program (outside of Eclipse) and see if I am still having issues with the program ceasing to execute. – cuckoo Jul 23 '14 at 04:40