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 !
;)

Similar Messages

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

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

  • How to use multiple statements inside the "THEN" block of CASE statement?

    Below is the code:
    SET @strTempString = case @strKeyMode
    WHEN 'AUTO/CYCLE'
    THEN  @strRefID + '|' + @strRetID
    WHEN 'CYCLE'
    THEN  @strRefID + '|' + @strRetID
    WHEN 'COMMERCIAL'
    THEN  @strRefID + '|' + @strRetID
    WHEN 'ISNAP'
    THEN  set @strFName = ltrim(rtrim((Left(dbo.CleanTheStringAdv(@strFName + '  ', 2) + '  ', 2))))
    '' + @strRefID + '|' + @strLName + '|' + @strFName + '|' + @strZIPorPolType
    WHEN 'ASNAP'
    THEN  @strRefID + '|' + @strRetID
    WHEN 'MOAT'
    THEN  @strRefID + '|' + @strRetID
    else '0'
    end 
    The first 3 conditions are understandable. How to use multiple statements in 4th case?
    Here I first want to set the value as:
    set @strFName = ltrim(rtrim((Left(dbo.CleanTheStringAdv(@strFName + '  ', 2) + '  ', 2))))
    and then return the string '' + @strRefID + '|' + @strLName + '|' + @strFName + '|' + @strZIPorPolType to @strTempString. 
    Please help me remove the syntax errors.
    Thanks in advance.

    Try below SQL
    DECLARE @strKeyMode varchar(20) = 'ISNAP'
    DECLARE @SQL VARCHAR(MAX)
    DECLARE @strRefID int=1
    DECLARE @strRetID INT=2
    --FIRST WAY
    IF @strKeyMode ='AUTO/CYCLE'
    SELECT CAST(@strRefID as varchar(10))
    ELSE IF @strKeyMode ='CYCLE'
    SELECT @sql = CAST(@strRefID as varchar(10)) + '|' + CAST(@strRetID as varchar(10))
    ELSE IF @strKeyMode='ISNAP'
    SELECT @sql = CAST(@strRefID as varchar(10)) + '|' + CAST(@strRetID as varchar(10))+'test'+'abc'
    ELSE
    SELECT @SQL='ABC'
    print @sql
    ----SECOND WAY
    SELECT @SQL = CASE @strKeyMode
    WHEN 'AUTO/CYCLE' THEN CAST(@strRefID as varchar(10))
    WHEN 'CYCLE' THEN CAST(@strRefID as varchar(10)) + '|' + CAST(@strRetID as varchar(10))
    WHEN 'ISNAP' THEN CAST(@strRefID as varchar(10)) + '|' + CAST(@strRetID as varchar(10))+'test'+'abc'
    ELSE 'No Record'
    END
    PRINT (@SQL)
    --Prashanth

  • Why its not a good idea to have a return statement in a finally block?

    deepak

    Finally executes after the try block has finished doing its work--either successfully or not. Finally is only for cleanup that has to be run after try finishes, regardless of how try completes. It's up to the try block to handle the business logic, the real work.
    If the real work in the try block says, "return x," then it is not appropriate for finally--the cleanup code--to alter that with "return y" or "throw new Exception()".
    If the real work in the try block throws an exception, it is not appropritae for the cleanup code to throw a different exception, or change that to a return.
    Remember, if you throw or return from within finally, that will superceded whatever your mode of completion in the try block was.

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

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

  • 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

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

  • Use of IF inside a Fix block

    Hi,
    I am having issues with use of IF inside a FIX ... END FIX block. I am trying to check for the value of a substitution variable inside a calculation script. Based on the value of the Subst Variable, statements inside the IF block should get executed.
    CALC Script 1 :
    FIX(x,y,z,"Final","Local",&SubstVariable1,&SubstVariable2)
    IF(&SubstVariable3="Yes")
    DataExport
    ENDIF;
    END FIX;
    CALC Script 1 above gives the warning message as "CALC command [IF] can only be used within a calc member block"
    Therefore I modified it as below
    CALC Script 2 :
    FIX(x,y,z,"Final",&SubstVariable1,&SubstVariable2)
    Local
    IF(&SubstVariable3="Yes")
    DataExport
    ENDIF;
    END FIX;
    This gives the error message as Error Parsing formula for Local, [(] without [)]
    Any help is appreciated.
    Thanks.

    You are still missing something after the DataExport:
    From the Tech Ref:
    For a text output file:
    DATAEXPORT "File" "delimiter" "fileName" "missingChar"
    For a binary output file:
    DATAEXPORT "Binfile" "fileName"
    For direct export to a relational database using ODBC:
    DATAEXPORT "DSN" "dsnName" "tableName" "userName" "password"
    Also, you need to set your DataExport options.
    SET DATAEXPORTOPTIONS
    DataExportLevel ALL | LEVEL0 | INPUT;
    DataExportDynamicCalc ON | OFF;
    DataExportDecimal n;
    DataExportPrecision n;
    DataExportColFormat ON | OFF;
    DataExportColHeader dimensionName;
    DataExportDimHeader ON | OFF;
    DataExportRelationalFile ON | OFF;
    DataExportOverwriteFile ON | OFF;
    DataExportDryRun ON | OFF;
    Also, I am assuming that you are running 9.3.1 or higher as this is when the dataexport option became available.
    Good luck
    Thanks,
    [EssbaseInfo.com|http://essbaseinfo.com]
    Edited by: EssbaseInfo on Apr 14, 2009 1:44 PM

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

  • 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

Maybe you are looking for

  • VBAP FIELD

    hi, i want to know the field in the table VBAP which do give the quantity of the material sold. thanks in advance.

  • Can you change image output resolution in Keynote?

    Is there a trick? I know it's nowhere obvious, but I find it'd be helpful -- I find Keynote the simplest way to create basic illustrations, but I need them at 150 DPI for printing. Obviously I could create a giant documents and manually dowsize, but

  • What is latest version of JSF that is used in J2ee 1.4?

    Hi Friends, JSF 1.2 or higher.what is softwarev requirements to use JSF.Please tell me Appliocation Server or Web server that can implement latest specification of JSF.Please reply as earlier as possible. Thanks Bye

  • Having a problem installing Flash Player 11.8

    Every time I try to install the latest version (11.8), an error message comes up and it says "Cannot Connect to Reliable Source." The installation gets to 47% and then stops. What does this mean? I've done the trouble shooting stuff like going into o

  • How to use Spry.Utils.extractParamsFromForm to get value of a form element

    Can we use Spry.Utils.extractParamsFromForm to get value of a form element ? I tried this quote: var cid = Spry.Utils.extractParamsFromForm('adForm','category'); Here the form name is adForm and category is an select item. This gives me error quote: