Basic (try catch finally)

Try catch and finally were thing i recently neglected to use unless my ide made me, but i was just reading on how to use them and I have a question about something i couldn't find an answer for:
objects you declare in try statements e.g.:
try{
BufferedReader br=...;
are only available in the scope of that try statement. Is this bad programming style or would "br" be automatically destroyed after the try statement is exited?

Well, define "dispose". If there's some method on the object that you need to call to clean that object up, you'll have to declare the variable outside the try block and then call it:
Something it;
try {
  it = SomethingFactory.createHeavyObject();
  it.doSomething(); // may throw Horse exception
  it.doSomethingElse();
} catch (Horse e) {
  e.printStackTrace();
} finally {
  it.releaseResources();
  it = null;  // only necessary if there will be a long time before "it" goes out of scope
              // and even then maybe not if releaseResources() took care of the heavy stuff
}On the other hand, you should never have to do this:
Something it;
try {
  it = new Something();
  it.doSomething(); // may throw Horse exception
} catch (Horse e) {
  e.printStackTrace();
} finally {
  it = null;
}Instead you could just do:
try {
  Something it = new Something();
  it.doSomething(); // may throw Horse exception
} catch (Horse e) {
  e.printStackTrace();

Similar Messages

  • Doubt try/catch/finally

    Hi all
    Say i have following program:
    try {
    line1.   functioncall()
    line2.    .....
    line3.    .....
    catch(..) {
    print error
    finally{
    System.out.println("In finally");
    }As per my understanding if there is some error in try block , then control will skip to catch and then to finally.
    And other way, if there is no error then all lines in try block will be executed and control has to go to finally block.
    And i see that there is no error (i have used try catch inside line1 function call also)
    Now I am facing this problem.
    In try block, line 1 is executed and getting into finally and there is also no error so it has skipped catch block. And in try block line2 and line 3 are skipped.
    Can anybody tell me why is it so.
    thanks
    Ravi

    What might be the problem?Sunspots. Not enough fiber. Government conspiracy.
    These are just guesses, which is all we can do unless you read and obey the following:
    Please post a short, concise, executable example of what you're trying to do. This does not have to be the actual code you are using. Write a small example that demonstrates your intent, and only that. Wrap the code in a class and give it a main method that runs it - if we can just copy and paste the code into a text file, compile it and run it without any changes, then we can be sure that we haven't made incorrect assumptions about how you are using it.
    Post your code between [code] and [/code] tags. Cut and paste the code, rather than re-typing it (re-typing often introduces subtle errors that make your problem difficult to troubleshoot). Please preview your post when posting code.

  • Comment on my use of try / catch / finally

    Below is a code fragment from an application I'm working on. I have a couple questions about it. Is the way that I'm using "finally" correct? It's supposed to make sure the Connection gets closed. Note that I have a separate class close the Connection.
    (ConnectionFactory is a class I wrote so I don't have to write the DB connection code over and over.)
            Connection con = null;
            try
                con = ConnectionFactory.getPooledConnection(Constants.JNDI_DS_NAME_LOCAL);
                Statement stmt = con.createStatement();
                stmt.executeUpdate("DELETE FROM person WHERE ID='" + personFormBean.getID() + "'");
            } catch (SQLException e)
                System.out.println(e.getMessage());
                e.printStackTrace();
            } finally
                ConnectionFactory.close(con);
            }Here's how I close the Connection:
        public static void close(Connection con)
            try
                if (con != null && !con.isClosed())
                    con.close();
            } catch (SQLException e)
                System.out.println(e.getMessage());
                e.printStackTrace();
        }My other question is about the code in the catch block. Is there anything different that should be done in the catch block?

    Below is a code fragment from an application I'm
    working on. I have a couple questions about it. Is
    the way that I'm using "finally" correct? It's
    supposed to make sure the Connection gets closed.
    Note that I have a separate class close the
    Connection.Excellent. I do this, too. (First person I had suggest it was jverd on this forum.)
    >
    (ConnectionFactory is a class I wrote so I don't have
    to write the DB connection code over and over.)
            Connection con = null;
    try
    con =
    con =
    con =
    ConnectionFactory.getPooledConnection(Constants.JNDI_D
    S_NAME_LOCAL);
    Statement stmt = con.createStatement();
    stmt.executeUpdate("DELETE FROM person
    FROM person WHERE ID='" + personFormBean.getID() +
    } catch (SQLException e)
    System.out.println(e.getMessage());
    e.printStackTrace();
    } finally
    ConnectionFactory.close(con);
    }Here's how I close the Connection:
        public static void close(Connection con)
    try
    if (con != null && !con.isClosed())
    con.close();
    } catch (SQLException e)
    System.out.println(e.getMessage());
    e.printStackTrace();
    }My other question is about the code in the catch
    block. Is there anything different that should be
    done in the catch block?Looks fine. I'd recommend that you add methods to explicitly close Statement and ResultSet, too. Call the method to close statement in the finally block before you close the Connection.
    I think logging the stack trace is the best thing to do. Printing the stack trace is okay, as long as someone can actually SEE the System.out stream. I think printing the message is a waste.
    Do you want commit/rollback logic for the DELETE?
    I'd pass the Connection into the method so it can participate in a unit of work. I don't have SQL methods get their own statement. Let the caller be responsible for obtaining and closing the Connection.
    CRUD operations in DAO is a nice pattern. I commend it to you.
    You do a lot right here, but I think it's possible to do better still.
    %

  • Mechanics of a Try-Catch-Finnally

    Could someone explain to me the mechanics of a try catch finally?
    as i understand it, you put the word try then a block then a catch and an exception
    like this
    try
    {...code...
    }catch (Exception e) {System.out.println ("error message"); continue}ok, say the try is wrong what happens next?
    this is my code.....and its bad.
    int bromstead=0;
    do {
                   System.out.print((bromstead + 1) + ". " + whereput);
                   try {
                   n = scan.nextInt();
                   r = scan.nextInt() - 1;
                   c = scan.nextInt() - 1;
                   }catch (Exception e) {System.out.println(compr + enter); continue;}//end of try
                   boolean goahead = (n <= 25 && n >= 1 && r >= 1 && r <= 5 && c >= 1 && c <= 5);
                   if (!goahead) {
                        System.out.println(range + enter);
                        continue;
                   squ.placer(n, r, c);
                   bromstead++;
                   if (bromstead % 5 == 0)
                        squ.display();
              } while (bromstead < 25);

    Just read this tutorial and you'll know all about exceptions and catching them. (And, that way, no one has to try to write a tutorial - that's already written!)
    http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html

  • About the finally block of the try catch.

    I know that finally block contains the code that will be executed in any condition of the try catch.
    However, I think it is unneccessary, since the stack after the try catch stack will be executed any way.
    Any one can help?
    for example
    try{
    System.in.read();
    catch(Exception e){}
    finally
    { System.out.println("does this matter?");}and
    try{
    System.in.read();
    catch(Exception e){}
    System.out.println("does this matter?");

    However, I think it is unneccessary, since the stackafter the try catch
    stack will be executed any way.That does assume that you catch and handle the error
    appropriately.
    Of course this is valid as well, and demonstrates
    when you would WANT a finally clause.
    Connection con = null;
    Statement stmt = null;
    try{
    con  = Database.getConnection();
    stmt = con.createStatement("Select * from dual");
    // maybe something throws an exception here?
    finally{
    if (stmt != null){
    stmt.close();
    if (con != null){
    con.close();
    The finally block here might throw a null pointer exception itself use
    null!=stmt null!=stmt

  • Try catch and finally

    Finally block should executed whether try goes successfully or the program goes to catch.
    Am I right?
    I have this kind of code here using BEA WLS:
         * @jpf:action
         * @jpf:forward name="success" path="reportView.jsp"
         * @jpf:forward name="error" path="../error.jsp"
        protected Forward viewReport(ViewReportForm vrForm)
            try{
                return new Forward("success");
            catch(Exception e){
                log.error(this,e);
                e.printStackTrace();
                getRequest().setAttribute("errorMessage",e.getMessage());
                return new Forward("error");
            finally
                try
                    if (conn!=null)
                        conn.close();
                    if (rs!=null){
                        rs.close();
                    if (stmt!=null)
                        stmt.close();
                    conn=null;
                    rs=null;
                    stmt=null;
                    array=null;
                    params=null;
                    query=null;
                    q_where_pp=null;
                    html=null;
                    *System.out.println("Testing finally block");*
                catch(Exception e)
                    log.error(e);
                    e.printStackTrace();
        }Note that I put System.out.println("Testing finally block"); to test whether finally block gets executed.
    When try goes fine which is return to page reportView.jsp the finally will be executed.
    But when it goes wrong which goes to error.jsp the finally block never print out the sentence.
    Which make me confuse, why finally block never executed after catch block.
    Anyone could help me?

    pramudya81 wrote:
    finally
    try
    if (conn!=null)
    conn.close();
    if (rs!=null){
    rs.close();
    if (stmt!=null)
    stmt.close();
    conn=null;
    rs=null;
    stmt=null;
    array=null;
    params=null;
    query=null;
    q_where_pp=null;
    html=null;
    *System.out.println("Testing finally block");*
    catch(Exception e)
    log.error(e);
    e.printStackTrace();
    First of all, your finally is after a bunch of statements, so if any of those statements throw an exception, your println() will never be executed. Finally does not mean that everything in the finally block gets executed even if they throw exceptions, it means execution will begin in the finally block before leaving the method try/catch.
    Second, closing connections, result sets, and statements can all throw exceptions (you know this because you put a try/catch block around it). And they're pretty much guaranteed to throw an exception in this case: Closing a connection closes all the statements associated with it (and closing a statement will close the resultset associated with it). So when you try to close the resultset, it's already closed. This should've showed up in your logs. You need to re-order your closes, and put each close in its own try/catch block.

  • Need HELP with finally() in nested try-catch

    hi,
    i am having trouble with deadlock and wondering if its due to an incorrect use of finally nested within multiple try catch blocks.
    is the inner finally() required, will the outer one get executed, or will the two finally() statements get executed...??
    the deadlock happens very infrequently to accurately test.
    try {
         try {
         catch (InterruptedException e) {
              return;
    catch {
    finally {
         //will this be executed be executed by the inner throw statement
    }or is an inner finally required
    try {
         try {
         catch (InterruptedException e) {
              return;
         //this finally is NEW....is it needed!
         finally {
              //will this be executed. will both get executed
    catch {
    finally {
         //will this be executed also, or completely ignored if exception throw from inner try/catch
    }

    inner/outer, which one is executed first?
    more info pls.I mean, really. How hard is it to find out for yourself?
    public class TestFinally {
        public static void main(String[] args) {
            try {
                try {
                    throw new RuntimeException("Whatever");
                } finally {
                    System.out.println("Inner finally");
            } finally {
                System.out.println("Outer finally");
    }I'll leave it to your imagination as to how to modify this class to confirm the answers to your original question.

  • 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

  • Exception handling with try/catch in acrobat

    Hi
    I have a problem using a try/catch block in my acrobat document-script. Try to enter the following into the debugger-console:
    try{nonexistentFunction();}catch(e){console.println('\nacrobat can't catch')}
    and run it. The output will be:
    nonexistentFunction is not defined
    1:Console:Exec
    acrobat can't catch
    true
    The whole point of a rty/catch block is for the application  NOT to throw an exception, but instead execute the catch-part of the  statement. However, acrobat does both: It throws an exception AND  executes the catch-block.
    Is there another way to suppress the exception, or to make the try/catch-block work as it's supposed to?

    > Also Adobe provides for free the JS or compiled file for Acrobat Reader to support the JS console.
    Where is that file located ? How to install it or where to place it ?
    What is the method referred by try67 on his site where he sells a product ?
    Is that the same as the compiled file you refer to ? or did he sell his solution to adobe ?
    It is helpful if people can get an idea of the nature of choices available and make informed decisions, than a cloak and dagger approach.
    For some jobs that we have, I have been very frustrated by a consultant who wont even give basic info for transparent billing despite all assurances for privacy, as a result we are forced to do the job ourselves.
    Dying Vet

  • Escaping Boolean & Try/Catch blocks

    Hi everyone-
    You all have been so great. I finally got my double/int and all working on my calculator. Now, I have one more question that I cannot figure out. My booleans to escape when form is not completed correctly are not working. That is, it will output error, but then still attempt the rest, giving printouts/general exception. I tried using another boolean, but not working. Here is the applet:
    www.quiltpox.com/HSTCalc.html
    and code: www.quiltpox.com/HSTCalc.java
       public void actionPerformed(ActionEvent evt) { //1
                     //declarations
             try{
              //reset all fields to null so user can start over
              if(source == button1)
                   text1.setText("");     
                   text2.setText("");
                   text3.setText("");
              if(source == button2)
                   //check that all fields have been completed
                   if(t1.length() == 0 || t2.length() == 0 || t3.length() == 0)
                            output.append("\nPlease complete the required fields and try again.");
                            verify = false;
                   //parse string into integer data and verify
                   if(verify)
                   //parsing
                   if(size == 0 || numOfSquares == 0 || WOF == 0)
                        output.append("\nYou have entered a null value for Square Size, " +
                             "\nQuantity of HSTs, and/or Fabric Width. Please try again. ");
                        verify = false;
                        proceed = false;
                   if(proceed)
                        all codes/printouts/methods
                   }     //end of if proceed
                   }     //end of verify
              }     //end of if
               }     //end of try
            catch (Exception e ) {
                    output.append("General Exception");
              finally {
                    textArea1.setText(output.toString());
       }     //end of action performed(i hope i quoted that right)
    Any ideas on how to resolve this? I know I could use a switch in a standard java, but not sure if that works with applet/try-catch.
    Thanks again,
    Kimberly

    You need to use "else" clauses here.if(t1.length() == 0 || t2.length() == 0 || t3.length() == 0)
      output.append("\nPlease complete the required fields and try again.");
    } else {
      if(size == 0 || numOfSquares == 0 || WOF == 0)
        output.append("\nYou have entered a null value for Square Size, " +
        "\nQuantity of HSTs, and/or Fabric Width. Please try again. ");
      } else {
        // all codes/printouts/methods

  • Try catch implementation in dynamic query

    I am fetching values by dynamic selection  (select a,b,..from (var)...) .
    Eveytime if I am selecting garbage value of var it will throw dump . Can u tell me how we implement try catch method / exception handling method so that I can avoid dump in dynamic query
    Appropriate answer will rewarded with points  that is for sure .

    Here is the usage  of th try statements ...
    PARAMETERS number TYPE i.
    DATA: result TYPE p LENGTH 8 DECIMALS 2,
          oref   TYPE REF TO cx_root,
          text   TYPE string.
    TRY.
        IF ABS( number ) > 100.
          RAISE EXCEPTION TYPE cx_demo_abs_too_large.
        ENDIF.
        PERFORM calculation USING    number
                          CHANGING result
                                   text.
      CATCH cx_sy_arithmetic_error INTO oref.
        text = oref->get_text( ).
      CATCH cx_root INTO oref.
        text = oref->get_text( ).
    ENDTRY.
    IF NOT text IS INITIAL.
      WRITE / text.
    ENDIF.
    WRITE: / 'Final result:', result.
    FORM calculation USING    p_number LIKE number
                     CHANGING p_result LIKE result
                              p_text   LIKE text
                              RAISING  cx_sy_arithmetic_error.
      DATA l_oref TYPE REF TO cx_root.
      TRY.
          p_result =  1 / p_number.
          WRITE: / 'Result of division:', p_result.
          p_result = SQRT( p_number ).
          WRITE: / 'Result of square root:', p_result.
        CATCH cx_sy_zerodivide INTO l_oref.
          p_text = l_oref->get_text( ).
        CLEANUP.
          CLEAR p_result.
      ENDTRY.
    ENDFORM.
    <b>please see this  link for detailed  explaination  of the TRY & ENDTRY  ...</b>
    <a href="http://">http://help.sap.com/saphelp_nw04/helpdata/en/a9/b8eef8fe9411d4b2ee0050dadfb92b/content.htm</a>
    reward  points if it is usefull......
    Girish

  • Please help with try/catch

    Hello, I'm writing a program and I got surprised with the following. I've got the following try/catch block:
    try {
    String param = config.getConfigValue("db2.driver");
    if (param == null)
    // parameter not defined.
    throw new Exception("Parameter 'db2.driver' missing!");
    else
    Class.forName(param);
    catch (SQLException sqlEx) {
    // do something
    catch (Exception e) {
    System.out.println("*** ERROR loading driver..."); (1)
    finally {
    releaseDB2Resources();
    I know the program flow goes through the finally block, but it doesn't print the message (1). Why is that? I don't understand it. What am I doing wrong?
    Thanks in advance.

    A finally block always gets executed, so that's why the println always works there. The only reason why the println in the catch wouldn't work is if that exception wasn't thrown. If a config value is not there, it might be the null string "" instead of null. Try this:
    if (param.equals(""))
    throw new Exception("blah");
    You could also try:
    if (true)
    throw new Exception("blah");
    to make sure that the exception is caught where you think it should be.

  • Problem with a Try/catch exception

    Hello everyone here on the forums. I'm brand new to Java and have a bit of a problem with a try catch statement I'm making. In the following code if a user enters a non-integer number the program will display "Sorry, incompatible data." Problem is it gets caught in a loop and continues to display "Sorry, incompatible data." My aim with the try catch was if the user is not quite smart enough to understand quadratic programs don't use symbols and characters it would state it isn't correct and continue running the program.
    Heres my code thus far:
    package finishedquadraticprogram;
    import java.util.*;
    * @author Matt
    public class quad {
         * @param args the command line arguments
        public static void main(String[] args) {
            boolean verification = true;
            double a, b, c, root1, root2, discriminant;
            Scanner keyInput = new Scanner(System.in);
            while ( verification)
            try
            System.out.println("a: ");
            a = keyInput.nextDouble();
            System.out.println("b: ");
            b = keyInput.nextDouble();
            System.out.println("c: ");
            c = keyInput.nextDouble();
            discriminant = Math.sqrt(b * b - 4 * a * c);
            root1 = (-b + discriminant) / 2 * a;
            root2 = (-b - discriminant) / 2 * a;
            verification = false;
            System.out.println("Root 1 = " +root1+ "\nRoot 2 = " +root2);
            } //try
            catch  (InputMismatchException iMe)
              System.out.println( "Sorry. incompatible data." );  
    }I'm pretty sure the problem is something to do with the keyboard buffer, but I'm not sure what I need to do to either reset it or clear it, whichever one works. (Oh, and how would I go about making the program use complex numbers? I realize Java can't use complex numbers and will just display NaN ... any ideas how to make this work?)
    Thanks a lot for all of your help guys, it's appreciated.

    this is better:
    package finishedquadraticprogram;
    import java.util.*;
    /** @author Matt */
    public class quad
       private static final double TOLERANCE = 1.0e-9;
       /** @param args the command line arguments */
       public static void main(String[] args)
          boolean verification = true;
          double a, b, c, root1, root2, discriminant;
          Scanner keyInput = new Scanner(System.in);
          while (verification)
             try
                System.out.println("a: ");
                a = keyInput.nextDouble();
                System.out.println("b: ");
                b = keyInput.nextDouble();
                System.out.println("c: ");
                c = keyInput.nextDouble();
                discriminant = Math.sqrt(b * b - 4 * a * c);
                if (Math.abs(a) < TOLERANCE)
                   root1 = 0.0;
                   root2 = -c/b;
                else
                   root1 = (-b + discriminant) / (2 * a);
                   root2 = (-b - discriminant) / (2 * a);
                verification = false;
                System.out.println("Root 1 = " + root1 + "\nRoot 2 = " + root2);
             } //try
             catch (InputMismatchException iMe)
                System.out.println("Sorry. incompatible data.");
                keyInput.next();
    }

  • Help regarding try catch!

    In the following code, when the exception occurs at b, the control goes to the catch block! however, though the values for c, d are perfect, they are never reached!
    Is there anyway to make the control return to where the exception was thrown & continue from there?
    int a=0,b=0,c=0,d=0,
    try {
              a = Integer.parseInt("11");
              b = Integer.parseInt("aa");
              c = Integer.parseInt("33");
              d = Integer.parseInt("44");          
         } catch(Exception ex) {
              System.out.println("Except occured: " + ex);          
         }

    No.
    If you want that other code to execute it would need a seperate try/catch block OR to go in the finally block. Whatever you feel.

  • Try catch trouble

    hi all, im quite new to java and am having a bit of trouble with a try catch statement
    try
              System.out.println("Enter your level: ");
              level = data.nextInt();
              while (!VLevel(level))
         System.out.println("Enter your level: ", LEVEL);
                   dstfloor = read_in.nextInt();
              catch(InputMismatchException exception)
    System.err.println("Invalid level");
    continue;
    the problem i have is that when it triggers the exception, it just repeats the 'invalid level' line infinitely. any ideas?
    thanks

    If this line is causing an exception: dstfloor = read_in.nextInt();Then dstfloor's value will not change.
    Because you are using continue in the catch, the loop will run unfinately with dstfloor having the same value.
    You will need to modify the dstfloor var either in the catch or in the finally.
    Edited by: Azzer_Mac on Apr 24, 2008 9:08 AM

Maybe you are looking for

  • IE8 in Windows 7 crashing with flash frequently

    Hello, I'm running a brand new install of Windows 7 (formatted with Windows 7 on a brand new drive, not upgraded from a previoius OS).  I'm running the 32 bit Internet Explorer 8.0.7600.16385 on a Windows 7 Ultimate x64 with all the latest MS patches

  • How to create my own Key for Rijndael (JCE Criptix)?

    I am developing a communication protocol and the key for encryption and decryption should be the user's password. This method generates a new RANDOM key: kg = KeyGenerator.getInstance("Rijndael"); kg.init(256); k = kg.generateKey(); The problem is th

  • Problems with activation after reset iphone!!!

    Good afternoon. I dropped my iphone 4 settings of the operating system of IOS 7 and I can not activate it. APPLE ID registered on which he does not fit after a reset. but this device registered in My Support Profile In my apple ID iphone 4 - Serial n

  • File-to-soap synchronous

    Hi I have a scenario where i have to create the file-soap synchronous   how we achieve that 1. Do i have to create the outbound message syn for file venkat

  • Hide the 'Download a copy' button from ribbon for sharepoint online.

    Hi,  I using SharePoint online, in that for a document library need to hide the 'Download a copy' button from ribbon.since from that document library no document to be downloaded. Regards, RK