Return statement at the end of try or after catch blocks

Hi
Can anyone tell me which is the better practice - to put the return statement at the end of try block or after all the catch blocks ie at the end of method.
Eg
Method A()
String str;
try{
str= [some code]
return str
catch(Exception e)
System.out.println("Exception");
} // end of method
OR
Method B()
String str;
try{
str= [some code]
}catch(Exception e)
System.out.println("Exception");
return str
} // end of method

I always try to work with only one exit point for each method.
For readability I always put the return statement as close to the end of the method as possible.
In this particular question,
I think you should put the return at the end of the method (for readability, since this is what you are
familiar with), but when I have a try-catch clause, I usually have an unrecoverable error and
should throw this further down the tree, so it usually becomes
try{
   return   
}catch(...){
   // write out some logging information
   rethrow exception or throw another exception
}I think you should NEVER reflect the occurence of an error in the return-value of the
method when an unrecoverable exception occurs. Just rethrow this exception or throw another method.
Other methods look like
   Object result = new...
   return result;As for the specific case of a repetitive if-case:
This is possible in two versions:
With one return and a result-object
Object result = new ...
if(..)
   result = ...
else if(..)
   result = ...
return result;With every time a return
if(...)
   return ...;
else if(...)
   return ...;For me the above two possibilities make no difference,
but I find the second version (which I hated when I began programming)
to be somewhat more of a (self-made) standard nowadays.
But I do not think this particular case makes much of a difference.
kind regards,

Similar Messages

  • Is it possible to export to PDF without a Return character at the end of every line?

    I am the author of a book whose first edition has been typeset and extensively amended in InDesign.  I now need to rewrite the first edition to produce a second edition.
    When I copy-and-paste from the PDF with which the publisher has supplied me into MS Word, I get a Return character at the end of every line, which means that text doesn’t automatically wrap and sentences are fragmented so that I get spurious grammar errors.
    I know that not all PDF files have a Return at the end of every line.  Is it possible to restrict Returns to the end of paragraphs when exporting from InDesign to PDF?  If so, what should the publisher be asking the typesetter to do?

    Thanks for your lightning-swift and helpful replies, Mike & Ellis.
    I don't have InDesign myself, so I know hardly anything about how it's used.  I'm just trying to research what an internationally-known publisher should already know how to do, but apparently doesn't!
    Following your suggestion, Mike, I have downloaded the trial version of Acrobat and exported the PDF to a Word file.  This has been moderately successful as there are far fewer spurious Return characters, just a few that I suspect may be hangovers from the typesetter having introduced soft returns in ID.
    As you've suggested Peter and Ellis, I'll suggest that the publisher asks the typesettter to export from ID to RTF and Text to see if that's even better.
    Message was edited 15:24 GMT by: AlanS5100

  • HT4623 I attempted to update the software of my dated iphone 3G. The version 4.2 downloaded and installed successfully on my phone...only to state at the end that "Your SIM does not seem to be supported. Please insert a supported SIM....". I can't even re

    I attempted to update the software of my dated iphone 3G last evening. My phone was constatantly connected with iTunes during the process. The iOS version 4.2 downloaded and installed successfully on my phone...only to state at the end that "Your SIM does not seem to be supported. Please insert a supported SIM....". It gives me no option on the phone other than making an Emergency call. I can't even restart or reboot the phone, or access springboard, etc. The black screen displays a USB cable plugged in to the iTunes logo. Incidentlly, I have been using this SIM for many months on this phone. I also tried inserting other functional SIMs. None of this works. Can someone help please!! Thanks,

    Maybe it was hacked before and now through the update it's locked back to the original carrier.

  • "Missing Return Statement" although the return statement IS there?

    Hello :) I am currently studying computing science at staffordshire university, java is one of my modules (first year) and im about half way through (still at introduction stage though)... Within my code apparently I have not returned a statement... yet to my believe the return statement is there and in the correct space, i would appreciate it if you could have a look and tell me where I am going wrong please:
    import java.util.*;
    public class ReadWriteArrayApp3
    +{+
    + public static void main(String [ ] args)+
    + {+
    + int[] nums = int double[6];+
    + double result;+
    + readArray(nums);+
    + printArray(nums);+
    + printReverse(nums);+
    + averageArray(nums);+
    result = averageArray(nums);
    + System.out.println("The average of your numbers is " + result);+
    + } // end main+
    public static void readArray(int [] a)
    + {+
    + Scanner kybd = new Scanner(System.in);+
    + System.out.println("Please enter 6 Integers");+
    + for(int i=0; i < a.length; i++)+
    + {+
    + a[i] = kybd.nextInt();+
    + }+
    + }+
    +public static void printArray(int [ ] b)+
    + {+
    + for (int i = 0; i < b.length; i++)+
    + {+
    + System.out.println(b);+
    + }+
    + }+
    + public static void printReverse(int [ ] c)+
    + {+
    + for (int i = c.length-1; i >= 0; i--)+
    + {+
    + System.out.println(c[i]);+
    + }+
    + }+
    + public static double averageArray(int [ ] d)+
    + {+
    + double sum, tot, average;+
    + for (int i = 0; i < d.length; i++)+
    + {+
    + tot = tot + d[i];+
    + average = (tot)/d.length;+
    + if ((average)=(tot/d.length))+
    + {+
    + sum = average;+
    +*  }
    + return sum;+
    + }+
    +} // end application class+
    Console states:
    javac  ReadWriteArrayApp3.java
    ReadWriteArrayApp3.java:49: missing return statement
    * ^*
    *1 error*
    Above in the code I have shown I have made a part bold... this shows the area in which console has a problem with.
    I would really appreciate any help in which I get
    Thankyou
    Victoria
    Edited by: StaffsUniJavaGirl on Nov 12, 2009 9:48 AM

    import java.util.*;
    public class ReadWriteArrayApp3
         public static void main(String [ ] args)
              int[] nums = int double[6];
              double result;
              readArray(nums);
              printArray(nums);     
              printReverse(nums);
              averageArray(nums);
              result = averageArray(nums);
              System.out.println("The average of your numbers is " + result);
         }  //  end main
         public static void readArray(int [] a)
              Scanner kybd = new Scanner(System.in);
              System.out.println("Please enter 6 Integers");
              for(int i=0; i < a.length; i++)
              a[i] = kybd.nextInt();
         public static void printArray(int [ ] b)
              for (int i = 0; i < b.length; i++)
                   System.out.println(b);
         public static void printReverse(int [ ] c)
              for (int i = c.length-1; i >= 0; i--)
                   System.out.println(c[i]);
         public static double averageArray(int [ ] d)
              double sum, tot, average;
              for (int i = 0; i < d.length; i++)
                   tot = tot + d[i];
                   average = (tot)/d.length;
                   if ((averagetot)=(tot/d.length))
                        sum = average;
         return sum;
    } // end application class*line 49 is bold*                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • HT1725 I downloaded an album from iTunes last night and some songs won't play through to the end. One stops after about 34 seconds and one stops after about 9 seconds every time. I am running the most up-to-date version of iTunes for Windows

    The album was Grateful Dead Sunshine Daydream Concert 8/27/72. Songs #11 and #12 start but don't finish on either my library or the ipod. There may be others too, but these two I noticed. The downloads were completed ok, the songs sync'ed ok and they appear to be the right length. I thought maybe I need to re-download them but how do you do that once they are purchased? Is there another issue? Thanks for your help
    Derek1466

    Depending upon what country that you are in (music can't be re-downloaded in all countries) then try deleting the incomplete tracsk from your iTunes library and redownload them via the Purchased link under Quicklinks on the right-hand side of the iTunes store home page on your computer's iTunes.
    If you aren't in a country where you can re-download music or if they re-download with the same problem then try the 'report a problem' page to contact iTunes Support : http://reportaproblem.apple.com
    If the 'report a problem' link doesn't work then you can try contacting iTunes support via this page : http://www.apple.com/support/itunes/contact/- click on Contact iTunes Store Support on the right-hand side of the page, then Purchases, Billing & Redemption

  • Compiler Error, Missing Return Statement

    This line of code for the begining of a method that reads a file always throws the compiler error, missing return statement. I can't figure out how to fix it!
    public String[] read(InputStream list) throws Exception {
    Could someone please help?

    you might need to post more code, but basically the
    compiler is complaining because you do not have a
    return statement at the end of your method.
    if you do not have a return statement (with a matching
    return type) then the compiler will complain. If you
    don't understand this then post the code to your
    method and we can get it fixed.
    public String[] read(InputStream list) throws
    Exception {
    String[] stringArray;
    return stringArray;
    The code is the most complex I have written so far but here is some of it. (the begining and the end)
    public String[] read(InputStream list) throws Exception {
    if (list != null) {
    String[] stringArray = null;
    try {
    while {
    //add strings to string array
    }//end of while
    return stringArray;
    }// end try
    catch{
    }//end of method

  • Besides throwing exceptions and the "return;" statement

    Besides throwing exceptions and the "*return*" statement, what else clauses could complete a code block abruptly?
    Originally I thought System.exit() should be one of that kind, and I was totally puzzled by the fact that finally clause dose not work with System.exit(). But after a few thoughts, it becomes clear to me that System.exit() dose not even complete a code block, let alone completing a code block abruptly. So is there other logic that could make a code block complete abruptly?
    My question originates from paragraphs in <Thinking in JAVA>, which claim that, I quote,
    "Unfortuantely, there's a flaw in Java's exception implementation. Although exceptions are an indication of a crisis in your program and should never be ignored, it's possible for an exception to simply be lost. This happens with a particular configuration using a finally clause"..."This is a rather serious pitfall, since it means that an exception can be completely lost, and in a far more subtle and difficult -to-detect fashion..."..."Perhaps a future version of Java will repair this problem"...
    After check with JLS, it seams that it is legitimate to ignore the reason for the abrupt completion of the try block, if the corresponding finally block completes abruptly. I think whether this is a "pitfall, flaw" or not depends on how deeply we language users understand the purpose of the finally clause and it is better for me to know all the possible reasons for a code block to complete abruptly.
    So, besides throwing exceptions and the "*return*" statement, what else clauses could complete a code block abruptly?

    warnerja wrote:
    Case 1: Normal flow (no exception is about to be bubbled to the caller before getting to the finally block) - I'd say we want an exception back due to the failure to close the stream.
    Case 2: The finally block was entered through an exception about to be bubbled to the caller - the caller can only get one or the other exception back, either the original exception or the one indicating the failure to close the stream. The finally block has no access to the pending exception however and is unaware of whether there is an exception pending or not. All it knows is an exception occurred during the execution of the finally block, and should throw that or wrap it in another exception - same handling as in Case 1.
    try {
      write();
      flush();
    finally {
      try {
        close();
      catch (...) {
        log();
    }The flush() at the end of try seems kind of redundant, since close() calls flush() anyway. The benefit is that the try statement completion matches the try block ("real work") completion.
    If we get to the end of the try block with no exception, then write() and flush() have succeeded and the data is where it needs to be. All that's left is to release the I/O resource, which will always be done in finally.
    If there's an exception in the try block, it is propagated out, so we know of any failure that occurred doing the "real work." The I/O resource is still released in finally.
    Regardless of how the try block completed, releasing the resource does not affect how the try statement completes, and hence does not supersede how our "real work" completes, which is all we care about. We still log any close() errors for later investigation. What matters to our program is whether all the data was written, and the completion of write() and flush() tells us that.

  • Return statement and Try Catch problem

    Hi!!
    I've got the next code:
    public ResultSet DBSelectTeam(String query) {
    try {
    Statement s = con.createStatement();
    ResultSet rs = s.executeQuery(query);
    return rs;
    } catch (Exception err) {
    JOptionPane.showMessageDialog(null, "ERROR: " + err);
    But I need a return statement in the catch-block, but I don't know what's the best option.
    Help...
    Many thanks.

    The error message is: "missing return statement", Yes, I know.
    You have to either return from the catch statement, or throw from the catch statement, or return or throw after the catch statement.
    The only ways your method is allowed to complete is by returning a value or throwing an exception. As it stands, if an exception is thrown, you catch it, but then you don't throw anything and you don't return a value.
    So, like I said: What would you return from within or after catch? There's no good value to return. The only remotely reasonable choice would be null, but that sucks because now the caller has to explicitly check for it.
    So we conclude that catch shouldn't return anything. So catch must throw something. But what? You could wrap the SQLE in your own exception, but since the caller is dealing with JDBC constructs anyway (he has to handle the RS and close it and the Statement), there's no point in abstracting JDBC away. Plus he has to deal with SQLE anyway in his use of the RS and Statement. So you might as well just throw SQLE.
    So since you're going to just throw SQLE anyway, just get rid of the try/catch altogether and declare your method throws SQLException

  • Return statement in catch block !

    Hello Java Gurus,
    The code is not compiling when i remove return from the catch block
    i dont really understand the essence of return statement in catch block
    any help is greatly appreciated !
    Thanks in advance !
    import java.io.*;
    public class fileinputstream  {
       public static void main(String arg[]) {
            FileInputStream fin ;
            FileOutputStream fout;
           try  {
                 fin =new     FileInputStream("input_file.txt");
                 int bytes_av = fin.available();
                 System.out.println("bytes available the input file "+bytes_av);
           catch(FileNotFoundException e)
               System.out.println("The input file is not present");
               return;
           catch(IOException e)
               System.out.println("error while giving bytes available the input file");
               return;
           try
                     fout =new FileOutputStream("output_file.txt");
           catch(FileNotFoundException e)
               System.out.println("The output file cannot be created");
               return;
           int data=0;
           try  {
               data =(int)fin.read();
           catch(IOException e) {
               System.out.println("Exception while reading from file");
            while(-1!=data)      {
                       try
                       fout.write(data);
                       catch(IOException e)
                           System.out.println("Error while writing to file");
                       try
                           data =(int)fin.read();
                       catch(IOException e)
                           System.out.println("Exception while reading from file");
            try  {
                   fin.close();
                   fout.close();
            catch(IOException e)  {
               System.out.println("Error while closing files");
    }

    You do understand what "return" means, don't you? It
    exits the method, main() in this case.
    So the return statements in the catch blocks end the
    program. If you remove the return statements, the
    program will continue with the code after the catch
    blocks. It needs the variables "fout" and "fin"
    there, and these must be initialised.
    If there are no return statements in the catch
    blocks, the variables "fin" and "fout" will be not
    initialized when you get to the code that uses them,
    and that's an error. The java compiler is telling you
    that you must always initialise the variables (you
    can set them to "null", for example).Great explanation !!!
    Thanks !

  • Missing return statement - Java noob here

    Hi to everyone! I'll just like to ask if anyone of you can check out my code and see why I can do to correct this 'Missing return statement' problem with my code.
    From what I've been noticing, the compiler returns this statement when the return statements are inside conditional clauses. Usually I've been able to remedy it by storing it into another variable that's been instantiated outside my usual 'if' statements. But this time, it was my first time to use a 'try' statement since FileReader and FileWriter won't work without it. I tried to use the same remedy but it just doesn't work. Here's the part of the code I'm having problems with:
    public String[] sortWordList()
             try
                  FileReader fReader = new FileReader("initlist.txt");
                  BufferedReader bReader = new BufferedReader(fReader);
                  String output = bReader.readLine();
                  String[] words = output.split(",");
                  for(int counter1 = 0; counter1 < words.length; counter1++)
                        for(int counter2 = counter1 + 1; counter2 < words.length; counter2++)
                                  if(words[counter2].compareToIgnoreCase(words[counter1]) < 0)
                                       String temp = words[counter1];
                                       words[counter1] = words[counter2];
                                       words[counter2] = temp;
                   String temp = "";
                   for(int counter1 = 0; counter1 < words.length; counter1++)
                        FileWriter fWriter = new FileWriter("initlist.txt");
                       fWriter.write(words[counter1] + "," + temp);     
                       fWriter.close();
                       temp = bReader.readLine();
                   String output2 = bReader.readLine();
                  String[] words2 = output.split(",");
                  return words2;
             catch(IOException ioe)
        }The compiler points the 'Missing return statement' at the last bracket.
    BTW, just for those who are wonder what we're making, our teacher gave us a machine project where we have to make a basic dictionary (words only, we'll be doing the definitions and other stuff that's associated with the word some other time I think) with input and sort functions.
    Thanks guys!
    - Alphonse

    T.B.M wrote:
    By doing this, we're subverting the exception mechanism and totally defeating the purpose of exceptions. If you're going to catch an exception, you should handle it. Just smothering it and returning null is not handling it. If you're not going to handle it, then don't catch it, or else catch it and wrap it in a more layer-appropriate exception and re-throw.Then ideally there should be some *"return String[];"* statement inside "catch", not after it.No. Not unless there's some meaningful default value to use when the file can't be read, which does not appear to be the case here.
    If you return null, or an empty String[], then the caller will have to do an if test to know that something went wrong and that the method failed to do what it was supposed to do, and then what is the caller supposed to do in that case? The point of exceptions is to avoid those explicit tests for errors and let the "happy path" code just go on under the assumption that things are fine. If something goes wrong, an exception will be thrown and the happy path code will stop excuting, without having to explicitly test for an error condition.

  • Return statement on a void?

    Theres a part that i dont understand, and if its possible i'd like to be helped a bit with it ^_^.
    This class is part of a program that uses threading to display a consistent "Tick Tock", but the part that i dont get is why is there a return statement on the method that is on bold, isn't void supposed to mean that it doesnt return a value, is the return statement just used to get out of the if loop?, or maybe something else! help is appreciated!
    class TickTock {
    synchronized void tick(boolean running) {
    if(!running) { // stop the clock
    notify(); // notify any waiting threads
    return;
    System.out.print("Tick ");
    notify(); // let tock() run
    try {
    wait(); // wait for tock() to complete
    catch(InterruptedException exc) {
    System.out.println("Thread interrupted.");
    synchronized void tock(boolean running) {
    if(!running) { // stop the clock
    notify(); // notify any waiting threads
    return;
    System.out.println("Tock");
    notify(); // let tick() run
    try {
    wait(); // wait for tick to complete
    catch(InterruptedException exc) {
    System.out.println("Thread interrupted.");
    }Message was edited by:
    Rix87

    A simple return statement means that you are just exiting that function. A function can use the return statement even if it is declared a void. It is just that from a void function you can not return a value.
    In your code the function is doing some condition checking (if statements) and based on that decides whether to exit the function or to continue going forward.
    Additionally, the if-construct is not a loop. If statements provide conditional branching mechanism.
    http://java.sun.com/docs/books/tutorial/java/nutsandbolts/branch.html
    You probably will never need to break out of an if statement. If you do need it, then perhaps your if condition is suspect.
    http://java.sun.com/developer/TechTips/2000/tt0613.html
    You can use labeled breaks if you need to break out of nested if statements but it is very rare that you will need them and the code can perhaps be written in another way which is much more readable than labeled breaks.

  • Return statements

    I have a project due that is a modifcation of a pervious project. It is a lottery game that will produce 104 sets of 6 unique numbers. I have a working version but am now trying to make it OO. I am to have 3 classes a main class, checkUser that implements CheckUserInterface, and getNumbers. I have figured most of it out but I need to return a boolean from the CheckUser class to the main class. I have the return statement in the checkUser class but am unable to refrence the boolean in main. I have named the boolean errors. When I try to refrence errors the complier says unable to resolve symbol. If any can give ant insight it would be greatly appreciated!! ;0) kristin

    Prolly need to post the code.
    Between
    [code]
    Program here
    [/code]
    tags, please.

  • Wifi works poorly on my brandnew ipad2. can some one help me or shall I return it to the store?

    Wifi works poorly to none on my brandnew (three days old) ipad2.
    The same Wifi connection works perfectly with my PC laptop.
    Can some one help me or shall I return it to the store?

    Try here...
    Apple - Support - iPad - Wi-Fi

  • Missing return statement. Why?

    Hi guys this might be an easy one for you all.
    I am receiving the error below when compiling the class below. Any idea what kind of statement I should be returning?
    Database.java:51: missing return statement
    ^
    1 error
    public Item search(String title){
         String ItemName;
         for (int i=0; i < items.length; i++)      {
             System.out.println (items);
    ItemName = items[i].getTitle(); // polymorphism
    if (ItemName.equals(title)) {
    System.out.println ("Match Exists!");
    } else {
    System.out.println ("No matches found");

    hi
    I am sorry to disturb u.this code will work fine .pls go throw the code.we have to add return statement in the two place.previously it was in loop only.Let me know the response pklease .public Item search(String title){
         String ItemName;
         for (int i=0; i < items.length; i++)      {
             System.out.println (items);
    ItemName = items[i].getTitle(); // polymorphism
    if (ItemName.equals(title)) {
    System.out.println ("Match Exists!");
    return items[i];
    } else {
    System.out.println ("No matches found");
    return null;
    return null;

  • Return statement inside AddEventListener?

    I am writing a custom function that will add a component to
    the stage. However, I want to postpone adding this component until
    some data has been loaded. Problem is that placing the return
    statement inside the Event handler function won't work, because it
    would be interpreted as a return statement for the Event handler
    function. Is there a way to for instance refer to the parent
    function?

    "Jurgen Beli?n" <[email protected]> wrote in
    message
    news:gq7jbs$7i4$[email protected]..
    >I am writing a custom function that will add a component
    to the stage.
    >However,
    > I want to postpone adding this component until some data
    has been loaded.
    > Problem is that placing the return statement inside the
    Event handler
    > function
    > won't work, because it would be interpreted as a return
    statement for the
    > Event
    > handler function. Is there a way to for instance refer
    to the parent
    > function?
    >
    > private function addDrawer(...):Drawer {
    > var newDrawer:Drawer = new Drawer();
    >
    > drawerContentLoader.addEventListener(Event.COMPLETE,
    function
    > (event:Event):void {
    > newDrawer.DrawerContentXml =
    XML(drawerContentLoader.data);
    >
    > // return newDrawer when loaded.
    >
    > });
    > drawerContentLoader.load(drawerContentRequest);
    >
    > return newDrawer;
    > }
    Why not just put your logic inside the handler for the event
    where the data
    exists for you to actually be able to populate it?

Maybe you are looking for

  • Help me get rid of "extra" monitor

    Hi, this is my first apple computer, but definitely not the first computer I've boloxed up. I need help to figure out how to disconnet the Mini DVI to VGA adapter without messing up the mini display port to HDMI basically: Mac Mini 2 ghz intel, 4 gb

  • Foreign Currency valuation- balance sheet preparation valuation

    Hi, I have a doubt in foreign currency valuation. When we tick Balance sheet preparation valuation ( in t-code F.05), no reverse postings are generating, eventhough i tick reverse postings. why is this happening?. What is happening when we use Balanc

  • Need help with a JavaScript to generate random number

    Hi First things first. I don't know the J of JavaScript. When I was thinking of some readymade solution to generate a random number in Captivate, I found this on a LinkedIn forum. 1) Add a user variable to your project called "randomNumber". It's val

  • No "Deleted Users" folder

    I used the Migration Assistant to transfer a user's settings and files from one laptop to another. The user's account had already been manually created on the new laptop, and contained some files I wanted to keep. During the migration, I received a d

  • Taxline itmes at Business Area level

    HI Gurus, My client wants Tax line itmes at Busienss Area level. Please help me on validation and substitutions to post taxline itmes at business area level. Below is the Scenario: Input Tax Purchase A/c--------------Dr (Business Area) Input Tax A/c-