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 !

Similar Messages

  • If statements in catch blocks

    Can you use if statements in catch blocks?
    (See below) Any help would be appreciated..
    catch (Exception e)
    // System.out.println("input error");
    if (deposit < 0)
    System.out.println("input error");
    System.out.println( "Balance is "+ patricksChecking.getBalance());

    Not only is there no good to catching an exception that's never thrown, as the previous-previous poster pointed out, you won't even be able to compile.
    For those who are not using the finally bloc in exception handling, it can be indispensible.

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

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

  • 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

  • Unreachable statement error occured while using return statement.

    Consider this code
    class q25{
         public static void main(String args[]){
              amethod(args);
         public static void amethod(String args[]){
              String str;
              try{
                   str = "Hello "+args[0];
                   System.out.println(str);
                   System.out.println("Returning to caller");
                   System.exit(0);
              catch(Exception e){
                   System.out.println("Exception ocured");
                   System.exit(0);          
              finally{
                   System.out.println("In finally");
              System.out.println("At the end of method");     
    }Above code compiles and runs successfully without any errors.
    Now consider below code which is same as above one except "System.exit(0)" statements were replace by "return" statements. Below code when compiled gives error as
    "q25.java:22: unreachable statement
    System.out.println("At the end of method");
    ^
    1 error"
    One thing i didn't understood in this context that, the above code when compiled should get same error as stated above. But not. It is obvious that presence of System.exit(0) must generate unreachable statement same as when it is replaced by "return" statement. What is the difference in getting the error for above but not for below code. Pls anyone help.
    class q25{
         public static void main(String args[]){
              amethod(args);
         public static void amethod(String args[]){
              String str;
              try{
                   str = "Hello "+args[0];
                   System.out.println(str);
                   System.out.println("Returning to caller");
                   return;
              catch(Exception e){
                   System.out.println("Exception ocured");
                   return;     
              finally{
                   System.out.println("In finally");
              System.out.println("At the end of method");     
    }

    warnerja wrote:
    masijade. wrote:
    Since you have a "return" in both the try and the catch portions of the try/catch block *(the second of which you should never do)* , anything thing that comes after the try/catch/finally blocks will be unreachable.That is not true. There are plenty of reasons to return from a catch block. If you handle the exception instead of rethrowing it or another exception, then you'll need a return somehow, either there or after the catch block. What you should never do is "return" in a finally block, because that will mask any exception in flight about to be thrown to the caller.Perhaps masijade's use of never is too strong, but I too prefer/tend to avoid using return anywhere in try/catch/finally to avoid potential gotchas. Consider:
    public class TryCatchFinally
      public Data process(String s)
        Data returnData = new Data();
        try
          returnData.value = Integer.parseInt(s);
          returnData.message = "Success";
          return returnData;
        catch (Exception ex)
          returnData.value = -1;
          returnData.message = "Fail";
          return returnData;
        finally
          returnData.value = 42;
          returnData.message = "?";
      public static void main(String[] args)
        TryCatchFinally demo = new TryCatchFinally();
        Data d = demo.process("2");
        System.out.println(d.message + ": " + d.value);
        d = demo.process("2.1");
        System.out.println(d.message + ": " + d.value);
      class Data
        int value = 0;
        String message = "";
    }

  • Return statement inside a catch block???

    If you put a return statement inside of a catch block, what statements will be executed next? I.e., what happens to the flow of control?

    If you put a return statement inside of a catchblock, what statements will be executed next? I.e.,
    what
    happens to the flow of control?If you write a short testing sample, compile it and
    run it, what do you get as a result ?
    Eek! That actually involves effort! Are you kidding?Kidding ? Me ?
    I'd better waste my time writing programs for lazy OPs !
    ;)

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

  • Return statement in a try catch block

    Hi friends
    Take a look in the code bellow
    try
    return (true)
    finally
    System.out.println("blabla");
    If nothing strange hapens in the try code, the return statement will be achieved. In this case, what will hapen ? The code in the finally block will be executed ??
    thanks

    If nothing strange hapens in the try code, the return
    statement will be achieved. In this case, what will
    hapen ? The code in the finally block will be executed
    ??Yes. Hence the word "finally".

  • Return in finally block hides exception in catch block

    Hi,
    if the line marked with "!!!" is commented out, the re-thrown exception is not seen by the caller (because of the return in the finally block). If the line is commented in, it works as I would expect. Is this is bug or a feature? I assume the return removes the call to troubleMaker() from the call stack - including the associated exception...
    Christian Treber
    [email protected]
    public class ExceptionDemo extends TestCase
    public void testException()
    String lResult = "[not set]";
    try
    lResult = troubleMaker();
    System.out.println("No exception from troubleMaker()");
    } catch(Exception e)
    System.out.println("Caught an exception from troubleMaker(): " + e);
    System.out.println("Result: " + lResult);
    public String troubleMaker()
    boolean lErrorP = false;
    try
    if(6 > 5)
    throw new RuntimeException("Initial exception");
    return "normal";
    } catch (RuntimeException e)
    System.out.println("Caught runtime exception " + e);
    lErrorP = true;
    throw new RuntimeException("Exception within catch");
    } finally
    System.out.println("Finally! Error: " + lErrorP);
    if(!lErrorP)
    return "finally";

    This is specified in the Java Language Specification, section 14.19.2 .
    -- quote
    If execution of the try block completes abruptly because of a throw of a value V, then there is a choice:
    * If the run-time type of V is assignable to the parameter of any catch clause of the try statement, then the first (leftmost) such catch clause is selected. The value V is assigned to the parameter of the selected catch clause, and the Block of that catch clause is executed. Then there is a choice:
    o If the catch block completes normally, then the finally block is executed. Then there is a choice:
    + If the finally block completes abruptly for any reason, then the try statement completes abruptly for the same reason.
    -- end quote
    "completing abruptly" (in this instance) means a throw or a return, as specified in section 14.1
    Ok? It's not a bug, it's the defined behaviour of the language. And when you think about it, this behaviour gives you the option to do what you want in your finally block.

  • Return statement should put beyond try/catch clause??

    The return statement should put beyond the try/catch clause, is that correct? Well,
    I tried to put inside the try block, but it will have compile error though.
    public String getValue()
         String value;
         try
         catch(...)
         return value;
    please advise. thanks!!

    When a method returns a value, you must make sure that even if an exception is thrown and caught a value will be returned (or just throw the exception out of the method).
    You can put a return clause as the last thing in the try block and another return clause after the catch block (this is where we go if we catch an exception so you probably want to return null).

  • 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

  • How to get the returned error messages in the Try/Catch block in DS 3.0?

    A customer sent me the following questions when he tried to implement custom error handling in DS 3.0. I could only find the function "smtp_to" can return the last few lines of trace or error log file but this is not what he wants. Does anyone know the answers? Thanks!
    I am trying to implement the Try/Catch for error handling, but I have
    hard time to get the return the msg from DI, so I can write it to out
    custom log table.
    Can you tell me or point me to sample code that can do this, also, can
    you tell me which tables capture these info if I want to query it from
    DI system tables

    Hi Larry,
    In Data Services XI 3.1 (GAd yesterday) we made several enhancements for our Try/Catch blocks. One of them is the additional of functions to get details on the error that was catched :
    - error_message() Returns the error message of the caught exception
    - error_number() Returns the error number of the caught exception
    - error_timestamp() Returns the timestamp of the caught exception.
    - error_context() Returns the context of the caught exception. For example, "|Session Datapreview_job|Dataflow debug_DataFlow|Transform Debug"
    In previous versions, the only thing you could do was in the mail_to function specify the number of lines you want to include from the error_log, which would send the error_log details in the body of the mail.
    Thanks,
    Ben.

  • RAISERROR with Try/Catch does not exit after exception in catch block

    I am trying to propogate an error from within my proc out to the caller.
    In the attached example I have 2 sets of try catch blocks.
    I raiserror in the first
    catch the error and then raiserror again. (I expect to exit)
    I do not expect :
    to get to print 'post test'
    to get to second try block.
    but this does not exit, instead the code flows as per 2 runs.
    I do not understand the reason for the flows, as it seems counterintuitive to be raising an error but then still print following exceptions. I cannot seem to find any references that explains this behaviour.
     running tests together results
    print '-------------------------------------------------------'
    print 'test 15'
    exec test_raiseerror 15
    print '-------------------------------------------------------'
    print 'test 16'
    exec test_raiseerror 16
    print '-------------------------------------------------------'
    print 'test 17'
    exec test_raiseerror 17
    print '-------------------------------------------------------'
    print 'test 18'
    exec test_raiseerror 18
    print '-------------------------------------------------------'
    'RESULTS'
    test 15
    error number provided: 15
    Msg 50000, Level 15, State 1, Procedure test_raiseerror, Line 21
    name hello 15
    post test
    15
    Msg 50000, Level 15, State 1, Procedure test_raiseerror, Line 37
    name hello 2 15
    post test2
    test 16
    error number provided: 16
    Msg 50000, Level 16, State 1, Procedure test_raiseerror, Line 21
    name hello 16
    post test
    16
    Msg 50000, Level 16, State 1, Procedure test_raiseerror, Line 37
    name hello 2 16
    post test2
    test 17
    error number provided: 17
    post test
    17
    post test2
    test 18
    error number provided: 18
    post test
    18
    post test2
    Msg 50000, Level 17, State 1, Procedure test_raiseerror, Line 21
    name hello 17
    Msg 50000, Level 17, State 1, Procedure test_raiseerror, Line 37
    name hello 2 17
    Msg 50000, Level 18, State 1, Procedure test_raiseerror, Line 21
    name hello 18
    Msg 50000, Level 18, State 1, Procedure test_raiseerror, Line 37
    name hello 2 18
    run tests seperately
    exec test_raiseerror 15
    error number provided: 15
    RESULTS 15
    Msg 50000, Level 15, State 1, Procedure test_raiseerror, Line 21
    name hello 15
    post test
    15
    Msg 50000, Level 15, State 1, Procedure test_raiseerror, Line 37
    name hello 2 15
    post test2
    exec test_raiseerror 16
    RESULTS 16
    error number provided: 16
    Msg 50000, Level 16, State 1, Procedure test_raiseerror, Line 21
    name hello 16
    post test
    16
    Msg 50000, Level 16, State 1, Procedure test_raiseerror, Line 37
    name hello 2 16
    post test2
    exec test_raiseerror 17
    RESULTS 17
    error number provided: 17
    post test
    17
    post test2
    Msg 50000, Level 17, State 1, Procedure test_raiseerror, Line 21
    name hello 17
    Msg 50000, Level 17, State 1, Procedure test_raiseerror, Line 37
    name hello 2 17
    exec test_raiseerror 18
    RESULTS 18
    error number provided: 18
    post test
    18
    post test2
    Msg 50000, Level 18, State 1, Procedure test_raiseerror, Line 21
    name hello 18
    Msg 50000, Level 18, State 1, Procedure test_raiseerror, Line 37
    name hello 2 18
     CODEBLOCK:
    if object_id('test_raiseerror','P') is not null
    drop proc test_raiseerror
    go
    create proc test_raiseerror(@id as int) as
    begin
    begin try
    declare @name varchar(20)
    select @name = 'hello'
    raiserror('name %s %d',@id,1,@name,@id)
    print 'next'
    end try
    begin catch
    declare @errormessage nvarchar(4000)
    declare @errornum int
    select @errormessage = error_message()
    , @errornum = error_severity()
    print 'error number provided: ' + convert(varchar(2),@errornum)
    raiserror(@errormessage, @errornum,1)
    print 'post test'
    end catch
    begin try
    select @name = 'hello 2'
    raiserror('name %s %d', @id,1,@name, @id)
    end try
    begin catch
    select @errormessage = error_message()
    , @errornum = error_severity()
    print @errornum
    raiserror(@errormessage, @errornum,1)
    print 'post test2'
    end catch
    end
    go
    sqlserver 2008 & 2008 R2

    There is a Connect that describes a similiar complaint.  But basically a raiserror inside a catch block does not terminate the procedure, it will continue with any additional code in the CATCH and FINALLY unless it hits a return statement.
    http://connect.microsoft.com/SQLServer/feedback/details/275308/have-raiserror-work-with-xact-abort

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

Maybe you are looking for

  • How do I install an SSD into my 2007 Macbook?

    Hi All, I did some searching online, but couldn't conclusively find a step-by-step procedure to installing an SSD into my 2007 Santa Rosa Blackbook. My mac has been running slow, and I've upped the memory to 2gb (I will be upping it to 4 shortly), bu

  • HT6147 I was expecting fix for some other issues in this update.

    In this Update I was expecting a Celular data and iTunes WiFi Sync fix. Issue on the Celular Data option is that after deactivatinh Cel-Data on some apps as soon as we leave that screen it turns back on. Many threads are started upon this issue. Clic

  • Jasper Parse Exception CRM HH Service

    I am getting a parse exception for the line in jsps that include this file -> "/include/HeadInclude.jsp". ated the following parse exception: org.apache.jasper.compiler.CompileException: C:\Documents and Settings\I806232\Documents\SAP\workspace\40SP0

  • Problem with SAPServerHost - Receiver Idoc

    Good afternoon! I am using the component SAP.Net Connector to receive IDOC's from the SAP, for this I created a Windows Service and in the OnStart event I create the SAPServerHost object that will go to talk with the SAP (through the transaction sm59

  • Updating a application question

    Ok so I have the game "NFS Shift" and it is 178MB. my ipod touch now has 6gb. There was a update available and when I click on download it is 170mb. does that mean when I finish downloading and syncing to my ipod touch, my ipod touch will have 5.8GB?