Nested try/catch for i/o exceptions

I read somewhere, which I can't find the url for, that this way is better:
ServerSocketChannel ssc;
ServerSocket ss;
try {                                                                         
    // wait for a connection                                                   
    try {                                                                      
        sc = ssc.accept();                                         
        sc.read(bb);                                               
    finally {                                                      
        if (sc != null) // in case accept() fails                          
            sc.close();                                            
catch (IOException e) {                                            
    log.error("accept, read, or close error", e);                  
}It seems more natural to me to do it the following way:
ServerSocketChannel ssc;
ServerSocket ss;
try {
    // wait for a connection                                               
    sc = ssc.accept();
    sc.read(bb);
catch (IOException e) {
    log.error("accept or read error", e);
finally {
    try {
        if (sc != null) // in case accept() fails                              
            sc.close();
    catch (IOException e) {
        log.error("close error", e);                          
}In the first case you have a nested try block in the first try with a finally to do the close(). In the second case the finally is part of the big try block and nested within the finally block is another try block for the close().
Does it matter?

(The second declaration should be SocketChannel sc.)

Similar Messages

  • Nested try-catch blocks

    Hello All,
    If I have 2 nested try-catch blocks see below
    try{
        //Some code
        try{
            //Code that throws an IOException
        }catch(NumberFormatException nfe){
            //Handle the NFE
    }catch(Exception e){
        //Handle the Exception
    }Now what happens if in the inner try-catch an IOException is thrown? Will it be ignored, or will it get thrown out to the outer one and be caught by that catch?
    Thanks,
    Matt

    Thanks, should have just done this from the start, but here is the result...
    The following code
    public class Main {
         public void execute(){
              try{
                  try{
                       for(int i=0;i<100;i++){
                            System.out.println(i);
                            if(i==5){
                                 throw new java.io.IOException();
                  }catch(NumberFormatException nfe){
                     System.out.println("caught in inner block");
              }catch(Exception e){
                  //Handle the Exception
                 System.out.println("caught in outer block");
         public static void main(String[] args) {
              Main m = new Main();
              m.execute();
    }GENERATES:
    0
    1
    2
    3
    4
    caught in outer block
    Thanks,
    Matt

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

  • Nested Try/Catch in a stored procedure going to outer

    I am using Service Broker to move data to a historical database and then delete it from the current table in a second stored procedure that gets the information passed to it; which I have working but what I am having trouble with is when there
    is an error in the second stored procedure rather than going to the catch in the second Stored procedure it goes back up to my first one.
    CREATE PROCEDURE [sp_PkgDelActivator_SB]
    AS
    BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    DECLARE @RecvReqDlgHandle UNIQUEIDENTIFIER;
    DECLARE @RecvReqMsg XML;
    DECLARE @RecvReqMsgName sysname;
    BEGIN TRY
    WHILE (1=1)
    BEGIN
    BEGIN TRAN
    --Get the top item on the queue.
    WAITFOR
    ( RECEIVE TOP(1)
    @RecvReqDlgHandle = conversation_handle,
    @RecvReqMsg = message_body,
    @RecvReqMsgName = message_type_name
    FROM DeleteReceiveQueue
    ), TIMEOUT 5000;
    IF (@@ROWCOUNT = 0)
    BEGIN
    ROLLBACK TRANSACTION;
    BREAK;
    END
    ELSE
    COMMIT TRAN
    EXEC sp_PkgDeleteHeap_SB
    @RecvReqDlgHandle = @RecvReqDlgHandle,
    @RecvReqMsg = @RecvReqMsg
    END
    END TRY
    BEGIN CATCH
    DECLARE @ERR_NR INT = ERROR_NUMBER(),
    @ERR_SVR_NR TINYINT = ERROR_SEVERITY(),
    @ERR_STT_NR TINYINT = ERROR_STATE(),
    @ERR_PRC_TE VARCHAR(50) = ERROR_PROCEDURE(),
    @ERR_LN_NR INT = ERROR_LINE(),
    @ERR_MSG_TE VARCHAR(1000) = ERROR_MESSAGE()
    IF @@TRANCOUNT > 0
    ROLLBACK TRAN
    INSERT INTO DB_ERR_LOG(
    ERR_NR,
    ERR_SVR_NR,
    ERR_STT_NR,
    ERR_PRC_TE,
    ERR_LN_NR,
    ERR_MSG_TE,
    LOG_DT)
    SELECT
    @ERR_NR,
    @ERR_SVR_NR,
    @ERR_STT_NR,
    @ERR_PRC_TE,
    @ERR_LN_NR,
    @ERR_MSG_TE,
    GETDATE()
    END CATCH
    END
    CREATE PROCEDURE [sp_PkgDeleteHeap_SB]
    @RecvReqDlgHandle UNIQUEIDENTIFIER,
    @RecvReqMsg XML
    AS
    BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    BEGIN TRY
    BEGIN TRANSACTION
    DECLARE @dtArrival date = 'gotten from somewhere else'
    IF @dtArrival BETWEEN '2014-07-01' AND '2014-09-30'
    BEGIN
    'Code to move and delete rows from a table'
    END
    ELSE IF @dtArrival BETWEEN '2015-01-01' AND '2015-03-31'
    BEGIN
    'Code to move and delete rows from a table'
    END
    ELSE IF @dtArrival BETWEEN '2015-04-01' AND '2015-06-30'
    BEGIN
    'Code to move and delete rows from a table'
    END
    END CONVERSATION @RecvReqDlgHandle WITH CLEANUP;
    END
    COMMIT TRAN
    END TRY
    BEGIN CATCH
    ROLLBACK TRAN
    DECLARE @ERR_NR INT = ERROR_NUMBER(),
    @ERR_SVR_NR TINYINT = ERROR_SEVERITY(),
    @ERR_STT_NR TINYINT = ERROR_STATE(),
    @ERR_PRC_TE VARCHAR(50) = ERROR_PROCEDURE(),
    @ERR_LN_NR INT = ERROR_LINE(),
    @ERR_MSG_TE VARCHAR(1000) = ERROR_MESSAGE()
    'Code to send the message back into the queue'
    INSERT INTO DB_ERR_LOG(
    ERR_NR,
    ERR_SVR_NR,
    ERR_STT_NR,
    ERR_PRC_TE,
    ERR_LN_NR,
    ERR_MSG_TE,
    LOG_DT)
    SELECT
    @ERR_NR,
    @ERR_SVR_NR,
    @ERR_STT_NR,
    @ERR_PRC_TE,
    @ERR_LN_NR,
    @ERR_MSG_TE,
    @END_TS
    END CATCH
    END
    Thanks for any help.
    Also if this is not the right area for this question I am sorry please tell me and I will try moving it to the right area.

    >>Please guide me how to create Stored Procedure and how to load datas into Flatfile table and from Flatfile Table to Parent and Child Table.
    Can you try loading the data using SSIS package ? If that's not an option , you could try OPENROWSET
    --from the linkUSE AdventureWorks2012;
    GO
    CREATE TABLE myTable(FileName nvarchar(60),
    FileType nvarchar(60), Document varbinary(max));
    GO
    INSERT INTO myTable(FileName, FileType, Document)
    SELECT 'Text1.txt' AS FileName,
    '.txt' AS FileType,
    * FROM OPENROWSET(BULK N'C:\Text1.txt', SINGLE_BLOB) AS Document;
    GO
    Satheesh
    My Blog |
    How to ask questions in technical forum

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

  • Yet another Try Catch question. Iterating through a ForEach loop

    Confused on error handling in a Powershell ForEach loop. I’m looping through a list of registry keys, attempting
     to open each one. If it succeeds, I do a bunch of stuff. If it fails, I want to skip to the next iteration.
    If I was doing It in VBScript I’d do this:
    For Each Thing In colThings
    Open Thing
    If Err.Number <> 0 Then
    “oops”
    Else
    Do stuff
    Do stuff
    Do stuff
    End If
    Next
    This is what I came up with in PowerShell. It seems to work, but just doesn’t seem powershell-ish. There must be a better way to use the catch output than just creating a $return variable and assigning it success or fail?
    ForEach ($subKeyName in $subKeyNames)
    try{$subKey = $baseKey.OpenSubKey("$subKeyName")}
    catch{$return = "error" }
    If($return -eq "error" )
    “Oops”
    Else
    Do stuff
    Do stuff
    Do Stuff

     
    I totally get what you're saying about formatting. I don't' have any habits yet, since I've only been working in Powershell since... well, what time is it now?
    Unfortunately, It Has Been Decreed that we are no longer to use VBScript for any engineering solutions at work, so my 15 years experience in it now needs to be transitioned over asap. I don't have the luxury of crawling before I run. I'm trying not to be
    frustrated, but it's like an English major waking up one day and being told "You must now speak French exclusively. Here's a book."
    The Do Stuff example of my ForEach loop is about 50 lines of code involving matching values in subkeys of this registry key with another and collecting output. I tried wrapping the whole thing in a try section based on some examples, but it seemed odd, that's
    why I'm asking. I'm used to tightly focused error handling at the point where an error may occur.
    In this example I'm only interested in whether or not I can open the subkey (it exists, but I may not have permission). If I can't, there's no point in continuing with this iteration of the loop, I want to skip to the next one. So why include all the "Do
    Stuff" in the the try section? From a readability viewpoint, it doesn't seem helpful.
    Also, there may be more error handling deeper in the code. If I then put that in a try/catch, and then something else inside that, now I have nested try/catches mixed in with nested if/elses, all wrapped in a For loop.
    Again, I can see how it works logically, but for readability not so much, and having all these braces 50 lines apart to match up is giving me eye strain :).
    It sounds like David is agreeing with jrv, that putting the entire ForEach loop code into a try/catch is the conventional way to do it. I guess it makes as much sense as putting it all in an If-else-Endif, and I just need to adjust my paradigm.
    But if not, my specific question was more along the lines of, is there a built in way to tell that the catch section has been executed, rather than me using it to populate an arbitrary variable and then read it? In VBScript, you execute something, and the
    next line, you check the Err.number. I wasn't sure if you could do that with a try/catch.

  • Catching a particular SQL Exception

    Hi
    I am getting an SQLException ORA-01653: unable to extend table.
    Is there any way so that I can catch this particular exception only.
    If I have a catch block
    catch(SQLException e)
    System.out.println(e);
    The above will be general and for all sql exception, I want to only catch ORA 01653 exception
    Thanks

    No, but what you can do is to test if this is the exception you want to special case in a local try - catch, then rethrow the exception if it's not a match.

  • Try-catch, new to java

    Anyone know how to effectivly exit a try catch statement if the exception is thrown? Heres this code I'm working with:
    public void create(){
         textCheck1 = textField1.getText();
         try{
           intCheck = Integer.parseInt(textCheck1);
         catch(IllegalArgumentException nfe) {
           System.out.println("NumberFormatException: Level must be a number between 1-70");
         if(intCheck>70){
             throw new NumberFormatException("NumberFormatException: Level must be a number between 1-70");
         else{
           TextArea.setText("Character Successfully Created");
           if(button1.isSelected()){
           System.out.println("Character: \n"+"Name: "+textField2.getText()+"\n"+"Job: "+box.getSelectedItem()+"\n"+"Level: "+textField1.getText()+"\n"+"Gender: Male"+"\n"+"Heroic: "+checkBox.isSelected()+"\n");
           else if(button2.isSelected()){
           System.out.println("Character: \n"+"Name: "+textField2.getText()+"\n"+"Job: "+box.getSelectedItem()+"\n"+"Level: "+textField1.getText()+"\n"+"Gender: Male"+"\n"+"Heroic: "+checkBox.isSelected()+"\n");
        }the way this is set up, when the catch block throws the exception the if-else executes anyway and the results are printed. If the string isn't formated correctly I want to throw the exception and exit the method. please help. thanks.

    cyberjed1 wrote:
    try{
    intCheck = Integer.parseInt(textCheck1);
    catch(IllegalArgumentException nfe) {
    System.out.println("NumberFormatException: Level must be a number between 1-70");
    }the way this is set up, when the catch block throws the exception the if-else executes anyway and the results are printed. If the string isn't formated correctly I want to throw the exception and exit the method. please help. thanks.Two flaws:
    1) You're catching IllegalArgumentException instead of NumberFormatException. The catch would never be entered.
    2) You're ignoring/swallowing the exception and doing a 'dumb' sysout instead of throwing the (new) exception.
    Fix your code as follows:
    try{
        intCheck = Integer.parseInt(textCheck1);
    } catch (NumberFormatException nfe) {
        throw new NumberFormatException("NumberFormatException: Level must be a number between 1-70");
    } Exactly the way as you did in the subsequent if block.
    By the way, if you consider yourself new to Java, why don't you make use of the 'New to Java' forum? Here we expect a bit more from you.

  • 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

  • Is it bad to put try/catch outside of for?

    Example:
    try{
    blah
    blah
    for(){
    blah
    blah
    blah
    blah
    }catch(Exception e){
    }Or is it better to do it like this:
    try{
    blah
    blah
    }catch(Exception e){
    for(){
    try{
    blah
    blah
    }catch(Exception e){
    try{
    blah
    blah
    }catch(Exception e){
    }Thanks

    As pervel said, it depends. Let's suppose you're going through a loop that's going to be executed 8 times, and on the third time an exception is thrown. If you can handle that exception and proceed with the other 5 trips through the loop, then the try-catch should be inside the loop to support that. If handling the exception means you aren't going to be doing the other 5 trips through the loop, then the try-catch should be outside the loop to support that. Saying that putting it inside -- or outside -- the loop is "bad" is thoughtless.

  • Doubt on try/catch exception object

    why it is not advisable to catch type exception in try catch block. Its confusing me. If i catch exception object then it will show whatever exception occured.
    btw, i was just go through duke stars how it works and saw this
    http://developers.sun.com/forums/top_10.jsp
    Congrats!

    Because there are many different kinds of Exception. If you have some specific local strategy for dealing with a particular excepion then you should be using a specific catch block.
    If you don't then you should allow the expection to end the program, and ideally you should deal with all the expceptions in one top-level handler, so you should throw, rather than catch the exceptions in your methods. Often at the outer most level of the program or thread you will actually catch Throwable (not just Exception) to deal with any unanticipated problems in a general kind of way.
    Also, you should be keeping track of what exceptions might be thrown, so that rather than using Exception in a throws clause or catch block, you should use the particular exceptions. Exceptions, generally, indicate a recoverable error that you really ought to be recovering from rather than just printing a stacktrace.
    That's why exceptions are treated differently from runtime errors.

  • Try/Catch Unknown Host Exception

    I need to validate for an error of Unknown Host Exception, in case someone tries connected to a server that doesn't exist, or types the wrong host name, so i can display a message. how do I do that, with a try catch block.
    I thought i would do:
    try{
          my code here such as...
          DatagramSocket socket = new DatagramSocket();
          // send request
          InetAddress address = InetAddress.getByName(args[0]);
          DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 4445);
          socket.send(packet);
        ...and so on, more code...
           socket.close();
    } catch (IOException e) {
           e.printStackTrace();
           System.out.println("Unknown host " + args[0]);
    }

    thanks, i also had to take out the e.printStackTrace(); and replace that with
    my error message and System.exit(0); and I got what i needed!

  • OutOfMemory Exceptions on Servlets, Try-Catch unable to help

    Hi, I'm playing with Java servlets right now and I seem to be getting some OutOfMemory errors. The weird thing is that even though I had identify the souce of error and tried to enclose it with a try-catch, the exception still occurs. Why is that so?

    OutOfMemoryError is actually a java.lang.Error, not a RuntimeException. So if you use a try/catch like this
    try {
      // stuff
    } catch (Exception e) {..}Errors will fall through, since Error is not a subtype of Exception. (Check the API.)
    You can catch it by catching Error or Throwable, like this:
    try {
      // stuff
    } catch (Error e) { //  this is rarely a good idea
    }But you normally wouldn't want to do this. When there's no memory left, there's not a whole lot you can do about it, and most of the code you might want to put inside the catch block will merely throw another OutOfMemoryError.
    As voronetskyy said, you're either creating too many (or too large) objects (typically in an endless loop), or you have specified too little memory for your application.

  • 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();
    }

Maybe you are looking for

  • Text in imovie?

    Sorry, I'm a bit of a newbie to imovie. Could anyone tell me if there is a way of adding text to a photo? Bascially I have a series of photos in imovie, and I want to show the picture & then have some text at the bottom - but the text is indivdual fo

  • Cannot create a file Loader Connection for Linux

    Im using ODQ 11.1.1.3 with the server installed on Linux and client on Windows. I have created a directory on the server for all my data files. The user (oracle) that starts the scheduler has full read write access to these directories. In Metabase M

  • Should I keep WIFI on?

    Should I keep WIFI on all the time when i am at home or school. I always have it on right now but i would like to know what is best....

  • AppleCare for iPod Question

    Hi, last month my on/off button of my iPod touch just broke. So I take it to Apple store and they gave me a new one. The question is . . . If I buy an applecare for ipod, which serial number should I apply with? The old one? or a new one?

  • Error in Infoview when viewing report

    Dear all, I am not sure what is happening here. My report runs fine under my computer however, when uploaded to the server and tried to run it, it says the following error message. CrystalReportViewer Error in File Lab Order Lifespan Report: Error in