Return statement in exception and consequences

Hi,
Can any one give me the explanation for my doubt?
Case 1:
I am having some code throwing some exception lets say arithematic exception in my try block.
I caught it in the catch block and at last I am having one finally?
as per normal order try block next catch block and at last finally will execute.
I execute the above code by putting a return statement inside catch block.I got the same order of execution irrespective of return statement inside catch?
What is the significance of return inside catch?
Case 2:
Lets take the scenario.
class MyException
     public static void main(String[] args)
          int i=1,j=0;
          try
               try
               System.out.println("the value is: "+(i/j));
               System.out.println("Inside try block");
               catch(ArithmeticException e)
               System.out.println("hi in ame");
               //return;
          finally
          System.out.println("inner finally");
                                        System.out.println("outer try");
          catch(Exception e)
                         e.printStackTrace();
               System.out.println("in exception");
          finally
               System.out.println("plz wait");
If return statement is there inside the inner try and catch the code out of inside outer try not getting executed Why So?
Any clarifications?
Thanking you,
Murthy.

First, please format your code as per http://forum.java.sun.com/features.jsp#Formatting
I'm not sure what part you don't understand.
.    public static void main(String[] args) {
.        try {
.            try {
.                throw new ArithmeticException();
.                System.out.println("Inside try block"); // #1
.            catch(ArithmeticException e) {
.                System.out.println("hi in ame"); // #2
.                return;
.            finally {
.                System.out.println("inner finally"); // #3
.            System.out.println("outer try"); // #4
.        catch(Exception e) {
.            System.out.println("in exception"); // #5
.        finally {
.            System.out.println("plz wait"); // #6
.    }#1 -- You won't get here because you throw AME.
#2 -- You will get here because you caught the AME you just threw.
#3 -- You will get here because it's a finally
#4 -- You won't get here. I think that this is what you're asking about: Why don't we get here? Because we've already done 'return' and this line is NOT inside a finally. The only things that can get executed after a return are finally blocks.
#5 -- You won't get here because you already caught the AME and didn't rethrow it or any other exception.
#6 -- You will get here because it's a finally.
Once you do a return, the only code you can execute before exiting the method are finally blocks. First the one corresponding to the try/cathc block where your return is, then the finally for the try/catch that encloses that one, and so on outward. The code between one finally and the next (#4 here) is NOT executed.
If you still have a question, please try to clarify exactly what behavior you don't understand.
Don't return from inside t/c/f.

Similar Messages

  • Return statement error and java.lang.noclassDefFoundError?

    public class Calculation
         public static void main (String[] args)
              int a[]=new int [12];
              int iNum=0;
              MainPrompt();
         static public int MyInput()
         return MyInput.readInt();
         public static boolean MainPrompt()
              System.out.println("\n This program will show you the times table [1-12] of any number between 1 & 100 inclusive.");
              int a[]=new int [12];
              int iNum = 0;
              do
                   do
                        System.out.print("\n Enter your number [1-100] or 999 to exit: ");
                        iNum = MyInput();
                        while ((iNum>=1)&&(iNum<=100));
                             if (iNum==999)
                                  System.out.println("\n Goodbye \n");
                        while (!(((iNum>=1)&&(iNum<=100))||(iNum==999)));
                             if ((iNum>=1)&&(iNum<=100))
                                  Calculation(a,iNum);
                                  TimesTable(a,iNum);
         public static void Calculation(int a[], int iNum)
              for(int j=0;j<a.length;j++)
              a[j]=iNum*(j+1);
         public static void TimesTable(int a[], int iNum)
              for(int i=0;i<a.length;i++)
              System.out.println((i+1)+"     *"+iNum+"     ="+a);
    In build output it says missing return statement line 42 "}"
    and also when I try to execute the program it gives me the Exception in thread "main" java.lang.NoClassDefFoundError: calculation
    In the folder I have placed the myinput.java and myinput.class file where my calculation.java is, but still no go.
    can anyone here help me out here?
    thanks in advance

    public class Calculation
         public static void main (String[] args)
              int a[]=new int [12];
              int iNum=0;
              MainPrompt();
         static public int MyInput()
         return MyInput.readInt();
         public static void MainPrompt()
              System.out.println("\n This program will show you the times table [1-12] of any number between 1 & 100 inclusive.");
              int a[]=new int [12];
              int iNum = 0;
              do
                   do
                        System.out.print("\n Enter your number [1-100] or 999 to exit: ");
                        iNum = MyInput();
                        while ((iNum>=1)&&(iNum<=100));
                             if (iNum==999)
                                  System.out.println("\n Goodbye \n");
                        while (!(((iNum>=1)&&(iNum<=100))||(iNum==999)));
                             if ((iNum>=1)&&(iNum<=100))
                                  Calculation(a,iNum);
                                  TimesTable(a,iNum);
         public static void Calculation(int a[], int iNum) //This part doesn't execute
              for(int j=0;j<a.length;j++)
              a[j]=iNum*(j+1);
         public static void TimesTable(int a[], int iNum)
              for(int i=0;i<a.length;i++)
              System.out.println((i+1)+"     *"+iNum+"     ="+a);

  • Doubts reg try block and return statements

    hi
    public int test()
              try
                   System.out.println("hi");
                   return 1;
              catch(Exception e)
              System.out.println("err");
              return 2;
              finally
                   System.out.println("final");
                   return 3;
              //System.out.println("after");
              //return 4;
    when i call this function, it will printing 3... why ??
    and also compilation error is coming when i put return statement after final block.. why is it so??

    but if commented the return statements in catcch and finally then it iam not getting any compilation error.
    public int test()
              try
                   System.out.println("hi");
                   return 1;
              catch(Exception e)
              System.out.println("err");
              // return 2;
              finally
                   System.out.println("final");
              //     return 3;
              System.out.println("after");
              return 4;
    and iam just learning ..... regarding return and try block

  • Return statement inside try block

    what is wrong if i write code like as below...please explain me since i am new to java
    class sample{
    public String method(){
    try{
    String str="abc";
    return abc;
    catch(Exception e){}
    }

    veldhanas wrote:
    return abc;In your code there is no varible declared as abc. It is a value assigned in str.
    Suppose if the code in try statement throws exception the return statement is skipped and the
    associated catch block will get executed. So your catch block must return a result of type String.... or throw another (or the same) exception.
    In this case, since there's no way the code in the given "try" block can throw an exception, it would have been better to not even have a try/catch block in the first place.
    And almost never just swallow exceptions like that (an empty catch block). There are only a few cases where it's ok to swallow them (such as in finally blocks where you're cleaning up resources which may throw exceptions while cleaning up, and you want to continue cleaning up and ignore those kinds of exceptions).

  • "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*                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Help with return statements

    Can someone explain to me what a return statement does exactly and how I would use it to return a value in the follwoing type of program.
    Its a array making program that allows up to 25 values with the value 0 stopping the method. I need to be able to display the how many usable values the user input (anywhere from 1-25).
    To do this I need to use a return statement, correct? if so, how do utilize it correctly if it is nesasary I will post the code itself.

    Heres what I have for the code...
    To simplify amounbt of typing(I wrote program in telnet) The beginning is a set of options using switch statement. 4 choices, 1)new data. 2) list the data 3) change the data and 4) exit.
    For the new data I need to have the user input up to 25 values or stop at any time by entering 0. the values also cannot be greater than 12000 or less than -12000. it should also return the number of usable values in the array. The return statement is what I am having trouble with.
    Code...
    static int NewData(double a[]) //This part is not changeable
    {   int 1;
    for(i=0; i<25; i++)
    {  System.out.print("Enter Element"+(i +1)+ "- ");
    a=MyInput.readDouble();
    if (a[i]>12000 || a[i]<-12000)
    {System.out.println("the last value is not valid");
                                 break;}
    if (a[i]==0)
    break;
    } return i;
    As of right now the method functions as is but two things need to be changed or added. If possible the program should now break if the user inputs an element greater than 12000 or less than -12000, it should just reset to the integer they were on. Also, how do I get the return value to display something? have i used it correctly to show the number of usable values ithe user entered?

  • Error when compiling - missing return statement

    Here is a simple piece of code
    class GoodDog {
         private int size;
         public int getSize() {
              return size;
         public int setSize(int s) {
              size = s;
         void bark() {
              if (size > 60) {
                   System.out.println("Woof! Woof!");
              } else if (size > 14) {
                   System.out.println("Ruff! Ruff!");
              } else {
                   System.out.println("Yip! Yip!");
    class GoodDogTestDrive {
         public static void main (String[] args) {
              GoodDog one = new GoodDog();
              one.setSize(70);
              GoodDog two = new GoodDog();
              two.setSize(8);
              System.out.println("Dog one : " + one.getSize());
              System.out.println("Dog two : " + two.getSize());
              one.bark();
              two.bark();
    when I compile it I get following message:
    C:\java>javac GoodDogTestDrive.java
    GoodDogTestDrive.java:11: missing return statement
    ^
    1 error
    don't understand why that is?

    tsith wrote:
    BigDaddyLoveHandles wrote:
    beandocks wrote:
    well after inserting a return statement code compiles and runs. why did I need to do a return here?
         public int setSize(int s) {
              size = s;
              return size; -- added this line
         }or you could loose the return type:
    public void setSize(int s) {
    size = s;
    Rather than tighten it?No, loose, not loosen.
    [http://www.merriam-webster.com/dictionary/loose%5B2%5D]
    As in, "Archers! Loose arrows!"
    So apparently he's advising to fling ints around to breach the walls. I think he must be suffering from low blood sugar. Somebody get that man a Malomar!

  • 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

  • Safari has frozen with a dialogue box open that simply makes a statement and then invites a single click on 'ok'. Unfortunately nothing happens except and audible error beep

    Safari has frozen with a dialogue box open that simply makes a statement and then invites a single click on 'ok'. Unfortunately nothing happens except and audible error beep

    MartinandJoanne wrote:
    Safari has frozen with a dialogue box open that simply makes a statement and then invites a single click on 'ok'. Unfortunately nothing happens except and audible error beep
    Are we to guess at the statement?

  • Problems with asynchronous(?) function call before return statement

    I have a function as following inside a class deriving from CustomNode:
    override protected function create () : Node {
                    parseContent();
                    return group;
            }parseContent() executes a HttpRequest and then a PullParser. At least that's what it should do. But actually, it doesn't. Is this because the HttpRequest is asynchronous and is "cancelled" because of the return statement? Or can't this be the problem?

    You would have to update or create the view in the finally block of the onOutput: or onInput methods within the request.
    You could also try
    var viewContent: Node;
    override protected function create () : Node {
                    parseContent();
                    FX.deferAction(function():Void{
                           viewContent = group;
                    return Group{ content: bind viewContent }
            }I never tried that, but it might work.
    Another option is to bind the parsed content to whatever view you are pushing it to. Then whenever the request is done, the view will populate its content on the change of the variable where the content is stored.
    Example:
    var allTables: TableModel[];      
    //***************start of table list decleration****************************\\
    public var list: SwingJList = SwingJList {
        var shortcutKey: Boolean = false;
        focusTraversable: true
        selectedIndex: 0
        action: function(){
            FX.deferAction(function():Void{
                openButton.fire();
        items: bind for( table in allTables ){
            table.name
    var searchDataXml = xmlGenerator.generateSearchXMLString(searchData);
    var contentLength: Integer = searchDataXml.getBytes().length;
    def postRequest: HttpRequest = HttpRequest {
        location: "{WEB_APPLICATION_REQUEST_URL}searchData/?database={DATABASE_KEY}";
        method: HttpRequest.POST;
        headers: [
                HttpHeader {
                    name: HttpHeader.CONTENT_TYPE;
                    value: "application/xml";
                HttpHeader {
                    name: HttpHeader.CONTENT_LENGTH;
                    value: "{contentLength}";
        onStarted: function() {
            println("onStarted - started performing method: {postRequest.method} on location: {postRequest.location}");
        onConnecting: function() { println("onConnecting") }
        onDoneConnect: function() { println("onDoneConnect") }
        onWriting: function() { println("onWriting") }
        onOutput: function(os: java.io.OutputStream) {
            try {
                os.write(searchDataXml.getBytes());
            } finally {
                println("onOutput - about to close output stream.");
                os.close();
                os.flush();
        onToWrite: function(bytes: Long) { println("onToWrite - entire content to be written: {bytes} bytes") }
        onWritten: function(bytes: Long) { println("onWritten - {bytes} bytes has now been written") }
        onDoneWrite: function() { println("doneWrite") }
        onReadingHeaders: function() { println("onReadingHeaders") }
        onResponseCode: function(code:Integer) { println("onResponseCode - responseCode: {code}") }
        onResponseMessage: function(msg:String) { println("onResponseMessage - responseMessage: {msg}") }
        onResponseHeaders: function(headerNames: String[]) {
            println("onResponseHeaders - there are {headerNames.size()} response headers:");
            for (name in headerNames) {
                println("    {name}: {postRequest.getResponseHeaderValue(name)}");
        onReading: function() { println("onReading") }
        onToRead: function(bytes: Long) {
            if (bytes < 0) {
                println("onToRead - Content length not specified by server; bytes: {bytes}");
            } else {
                println("onToRead - total number of content bytes to read: {bytes}");
        onRead: function(bytes: Long) {
            // The toread variable is non negative only if the server provides the content length
            def progress =
            if (postRequest.toread > 0) "({(bytes * 100 / postRequest.toread)}%)" else "";
            println("onRead - bytes read: {bytes} {progress}");
        var parser = new XmlPullParser();
        onInput: function(is: java.io.InputStream) {
            // use input stream to access content here.
            // can use input.available() to see how many bytes are available.
            try {
                allTables = parser.processResults(is);
            } finally {
                is.close();
        onException: function(ex: java.lang.Exception) {
            println("onException - exception: {ex.getClass()} {ex.getMessage()}");
        onDoneRead: function() { println("onDoneRead") }
        onDone: function() { println("onDone") }
    postRequest.start();
    } In this case an array of tableModel names are bound to the list view.
    When the httprequest ends, it sets the parsed tableModel array to the array declared in this class.
    The list view will populate the table names from the array when the request finishes.

  • Xmlgen.getxml("select * from table") returns null pointer exception

    I am running oracle 8i on solaris server and clinet on windows
    NT and i am this select statement
    select xmlgen.getxml("select * from table") from dual ,its
    returning null pointer exception,i have tried it through
    jdbc,even then its returning xml as
    <?xml version = '1.0'?>
    <ERROR>java.lang.NullPointerException</ERROR>
    can any body tell me the error.Help will be really appreciated.I
    need an urgent response,if some one can guide me please.
    My email is [email protected],if you can give me a quick
    response on this email,your effot will be appreciated.
    thanks
    Masood

    What is actually throwing the NullPointerException? rs.getMetaData() or table.setModel()?

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

  • Missing return statement error

    public class Member
             public int Member(String memberid, String memberpw)
         String cs = "jdbc:oracle:thin:@255.255.255.255:1000:a123stud";
             String user = "123456";
             String pass = "123456";
              String member = "member_id";
             try
                   Class.forName("oracle.jdbc.driver.OracleDriver");
                   //Connection conn = DriverManager.getConnection("jdbc:odbc:myOracle");
                   Connection conn = DriverManager.getConnection(cs,user,pass);
                   Statement stmt = conn.createStatement();
                   String query = "SELECT * FROM members";
                   ResultSet rs = stmt.executeQuery(query);
                 // ResultSet rs = stmt.executeQuery("SELECT * FROM members WHERE member_id = 'M0001'");
                        int counter = 0;
                        while(rs.next())
                             member = rs.getString("member_id");
                             counter++;
                             if (counter == 0)
                             return 0;
                             else
                             return 1;
                        //System.out.println("\nOracle10g at 255.255.255.255 is working!");
              catch(SQLException e)
                   System.out.println("\n\nException Occured " +
                             "(Incorrect IP address, Server may be down, or SQL Exception)");
                   e.printStackTrace();
              catch(ClassNotFoundException e)
                   System.out.println("\n\nException Occured (CLASSNOTFOUND Exception)");
    }It says i am missing the return statement,but i do have set return something,whats the error? thx for helping

    For example, what happens if the SQL query doesn't
    return any rows, and rs.next() is never true?The while() loop will be skipped and the if statement
    will execute, which has two branches, one of which is
    guaranteed to return?Oops. My bad.
    I thought the ifs were inside the while.
    Okay, the problem here is with the exception handling. Catching and logging and doing nothing else is usually almost as bad as just smothering them. In this case it's especially true because the method then just continues after the catch blocks, in which case there's no return.
    You have to actually handle the exceptions if you're not going to propagate them. In this case, that would mean returning some reasonable default value. I'd say that's not a good idea here, and you're better off to just let the exceptions be thrown, or wrap and rethrow in your own exception.

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

Maybe you are looking for

  • Emailing more than one photo per email message

    Newbie alert: I want to resize and send a handful of photos via email, can't figure out how. Thanks, Julie

  • IMac or Macbook Pro Can not Decide Need Help

    The iMac or Mac Pro I can't decide which is the best one to get and I need to get a good answer before next Thursday. The 24" iMac with extreme Intel processor or Macbook Pro 17" with 2.6 Intel Processor. I'm into Graphic Design in the winter months

  • Illustrator cs6 is freezing at start up

    I have adobe illustrator  cs6 on a Mac mini. I have been using it everyday for about 3 weeks. All my art is vector based. Today I clicked on the icon in my task bar. The icon did its regular jumping thing, then began to bounce much higher. The start

  • SIUD warnings and no esata expresscard..anymore

    After I upgraded from tiger to Leopard things are odd. My Siig esata 11, 2 port card doesn't work and I get this warning after running disk utility, Warning: SUID file "Applications/System Preferences.app/Contents/Resources/installAssistant" has been

  • Want to reset the Imac - Can't Login using Leopard

    I just got a brand new 24" Imac and upgraded it to Leopard following a transfer of all the files from my old imac. Then all problems started as I could not login as it does not recognise any password incl the admin one. I tried everything mentioned i