Try/catch code

I have a question concerning java try-catch blocks. Is there a way for java to catch multiple exceptions in one block? For e.g. by enclosing the try/catch block within a loop? Is this possible?
Thanks.
Liza

Thanks for your responses...that code i already know
however i found out since that java will only catch
one exception at a time, even if the try/catch block
of code is enclosed in a loop.That doesn't make any sense.
There is only ever one exception at a time. You might have to code to catch more than one type of exception, but only one is generated at a time.

Similar Messages

  • How to simulate a dml error in order to test try-catch code block inside a stored procedure

    Hi,
    What would be the easiest way to simulate a dml error in order to test a try catch block.
    I would like to do it with a simple command from outside the stored procedure if possible.
    I tried dropping the table that was updated but it hangs
    Thanks,
    Dani

    Dropping the table that is the target of the procedure will give you an unpleasant surprise: the CATCH block will not fire. To wit, errors like missing tables can only be caught in outer scopes, but not in the procedure where the error occurs.
    But you would add a fake constraint to a table which causes the update to fail. You need to do this in advance, not while running the procedure.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Why do I get a CATCHA code every time I try to send an e mail-just started recently

    why do I get a CATCHA code every time I try to send an e mail on safari-just started recently

    It's likely that AT$T is recognizing that version of Safari as not compliant with their anti-spam or security requirements for their webmail application. Assuming you are running OS X "Snow Leopard" that Safari version is the latest one. That's annoying because I am not aware of any noteworthy security improvements in subsequent Safari releases, and AT$T ought not to treat it any differently.
    Your alternatives are to upgrade your Mac's operating system, which has certain minimum hardware requirements, or simply use your Mac's Mail application. Or, just use Firefox when you want to use webmail. Otherwise you'll have to put up with their silly Captcha annoyances.
    To add your AT$T email account to Mail, start here: http://www.apple.com/support/macosx/mailassistant/
    To upgrade OS X start here: http://www.apple.com/osx/how-to-upgrade/

  • Compile time errors for large code in try-catch blocks

    Hi, Has anyone ever faced this problem of a compile time error, where the Java compiler returns with the following error that Code is too large for try block.
    I have about 5000 thousand lines in my try-catch block and am facing this problem. Please suggest possible solutions

    1) Are you sure that your try/catch blocks contain 5 million lines?! I seriously don't believe this.Sounds like generated code. The generator needs to be a bit cleverer. In particular, it seems to be generating repeated blocks of code that ought to be stuffed into methods somewhere.

  • Can't find class because of try catch block ?!

    Hello,
    I'm using the JNI to use a java library from my c++ code.
    JNI can't find the "Comverse10" class below, but when i put the try catch block in createMessage in comment, FindClass succeeds ?!
    Unfortunatly i need the code inside the try block ;-)
    I tried a few things, but none of them worked:
    - let createMessage throw the exception (public void createMessage throws ElementAlreadyExistsException ), so there isn't a try catch block in createMessage => result: the same
    - make a "wrapper" class Comverse that has a Comverse10 object as attribute and just calls the corresponding Comverse10.function. Result: Comvers could be found, but not constructed (NewObject failed).
    Can someone tell me what is going on ?!
    Thank you,
    Pieter.
    //Comverse10 class
    public class Comverse10 {
    MultimediaMessage message;
    /** Creates a new instance of Comverse10 */
    public Comverse10() {
    public void createMessage() {
    TextMediaElement text1 = new TextMediaElement("Pieter");
    text1.setColor(Color.blue);
    SimpleSlide slide1 = new SimpleSlide();
    //if i put this try catch block in comment, it works ?!
    try{
    slide1.add(text1);
    catch(com.comverse.mms.mmspade.api.ElementAlreadyExistsException e){}
    MessageContent content = new MessageContent();
    content.addSlide(slide1);
    this.message = new MultimediaMessage();
    message.setContent(content);
    message.setSubject("Mijn subjectje");
    for those of you who are intersted: here's my C++ code:
    //creation of JVM
    HRESULT Java::CreateJavaVMdll()
         HRESULT HRv = S_OK;
    char classpath[1024];
         jint res;
         if(blog)     this->oDebugLog->Printf("CreateJavaVMdll()");
         strcpy(classpath,"-Djava.class.path="); /*This tells jvm that it is getting the class path*/
         strcat(classpath,getenv("PATH"));
         strcat(classpath,";D:\\Projects\\RingRing\\MMSComposer;C:\\Progra~1\\j2sdk1~1.1_0\\lib");     //;C:\\Comverse\\MMS_SDK\\SDK\\lib\\mail.jar;C:\\Comverse\\MMS_SDK\\SDK\\lib\\activation.jar;C:\\Comverse\\MMS_SDK\\SDK\\lib\\mmspade.jar
         //------Set Options for virtual machine
         options[0].optionString = "-Djava.compiler=NONE"; //JIT compiler
         options[1].optionString = classpath;                                        //CLASSPATH
         //------Set argument structure components
         vm_args.options = options;
         vm_args.nOptions = 2;
         vm_args.ignoreUnrecognized = JNI_TRUE;
         vm_args.version = JNI_VERSION_1_4;
         /* Win32 version */
         HINSTANCE hVM = LoadLibrary("C:\\Program Files\\j2sdk1.4.1_01\\jre\\bin\\client\\jvm.dll");
         if (hVM == NULL){
              if(blog) oDebugLog->Printf("Can't load jvm.dll");
              return E_FAIL;
         if(blog) oDebugLog->Printf("jvm.dll loaded\n");
         LPFNDLLFUNC1 func = (LPFNDLLFUNC1)GetProcAddress(hVM, "JNI_CreateJavaVM");
         if(!func){
              if(blog)     oDebugLog->Printf("Can't get ProcAddress of JNI_CreateJavaVM");
              FreeLibrary(hVM);     hVM = NULL;
              return E_FAIL;
         if(blog)     oDebugLog->Printf("ProcAddress found");
         res = func(&jvm,(void**)&env,&vm_args);
         if (res < 0) {
    if(blog)     oDebugLog->Printf("Can't create JVM with JNI_CreateJavaVM %d\n",res);
    return E_FAIL;
         if(blog)     oDebugLog->Printf("JVM created");
         return HRv;
    //finding Comverse10 class:
    HRESULT CALLAS MMSComposer::InitializeJNI(void)
         HRESULT HRv=E_FAIL;
         DWORD T=0;
         try
              if(blog)     oDebugLog->Printf("\nInitializeJNI()");
              bJVM = FALSE;
              jni = new Java(oDebugLog);
              if(jni->CreateJavaVMdll()!=S_OK){
                   if(blog)     oDebugLog->Printf("CreateJavaVMdll() failed");     
                   return HRv;
              jclass jcls = jni->env->FindClass("Comverse10");
              if (jcls == 0) {
    if(blog)     oDebugLog->Printf("Can't find Comverse10 class");
                   jclass jcls2 = jni->env->FindClass("test");
                   if (jcls2 == 0) {
                        if(blog)     oDebugLog->Printf("Can't find test class");
                        return HRv;
                   if(blog)     oDebugLog->Printf("test class found %08x",jcls2);
    return HRv;
              if(blog)     oDebugLog->Printf("Comverse10 class found %08x",jcls);
              jmethodID mid = jni->env->GetMethodID(jcls , "<init>", "()V");
              if (mid == 0) {
                   if(blog)     oDebugLog->Printf("Can't find Comverse10() constructor");
    return HRv;
              if(blog)     oDebugLog->Printf("Comverse10() constructor found");
              jobject jobj = jni->env->NewObject(jcls,mid);
              if(jobj==0)
                   if(blog)     oDebugLog->Printf("Can't construct a Comverse10 object");
    return HRv;
              if(blog)     oDebugLog->Printf("Comverse10 object constucted");
              //Create Global reference, so java garbage collector won't delete it
              jni->jobj_comv = jni->env->NewGlobalRef(jobj);
              if(jni->jobj_comv==0)
                   if(blog)     oDebugLog->Printf("Can't create global reference to Comverse10 object");
    return HRv;
              if(blog)     oDebugLog->Printf("global reference to Comverse10 object %08x created",jni->jobj_comv);
              bJVM=TRUE;
              HRv=S_OK;
         }     catch( IDB * bgError ) { throw bgError->ErrorTrace("InitializeJNI::~InitializeJNI",HRv, 0, T); }
              catch(...) { throw IDB::NewErrorTrace("InitializeJNI::~InitializeJNI",HRv, 0, T ); }
              return HRv;

    >
    I would guess that the real problem is that that the
    exception you are catching is not in the class path
    that you are defining.Thanks jschell, that was indeed the case.
    I don't have the docs, but I would guess that
    FindClass() only returns null if an exception is
    thrown. And you are not checking for the exception.
    Which would tell you the problem.Ok, i'll remember that. But what with exceptions thrown in my java code, the documents say
    // jthrowable ExceptionOccurred(JNIEnv *env);
    // Determines if an exception is being thrown. The exception stays being thrown until either the native code calls ExceptionClear(), or the Java code handles the exception
    so, what if the java code throws an exception and catches it, will i be able to see that in my c++ code with ExceptionOccurred ?
    or
    should the java method be declared to throw the exception (and not catch it inside the method)
    Again, thank you for your help, it's greatly appreciated !

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

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

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

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

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

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

  • 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

  • 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

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

  • Performance impact on using too much try catch block

    I have several questions here:
    1. The system that I'm developing requires to be high performance, but I am not sure how will try catch block affect overall performance.
    2. I wanted to know which would be more efficient (result in faster processing)
    Have several generic try catch OR catch all exceptions individually?
    ex:
    try {
    } catch (Exception e){
    }vs.
    try{
    } catch (MalformedUrlException me){
    } catch(SQLException){
    }3. Which one would be faster, one big try catch block or several small try catch blocks?
    ex.
    try{
    //read from io file
    //query database
    //parse data
    //write to file
    //query database again
    } catch(Exception e){
    //log exception
    }vs.
    try{
    //read from io file
    } catch(FileNotFoundException fnfe){
    //log exception
    try{
    //query database
    }catch(SQLException se){
    //log exception
    try{
    //parse data
    }catch(SaxParserException saxe){
    //log exception
    try{
    //query database again
    }catch(SQLException se2){
    //log exception
    try{
    //write to file
    } catch(FileNotFoundException fnfe){
    //log exception

    1. The system that I'm developing requires to be high performance, but I am not sure how will try catch block affect overall performance.Compared to what? You can't write an equivalent program that doesn't have a try-catch block, so the answer would have to be that it doesn't affect performance at all.
    2. I wanted to know which would be more efficient (result in faster processing)Have several generic try catch OR catch all exceptions individually?
    You still have it backwards. Do you need to do different things for different exceptions? If so, then that's what you have to do and there is no other code that might be "faster".
    Here's what you should do. Write the code that needs to be written. Don't leave out necessary stuff because of performance reasons. (If you left out all your code, the program would run much faster.) Then find out which parts of the program ACTUALLY take the most time and work on speeding them up.

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

    This may be too vague of a question but is it bad practice to use one large try catch block? In my mind it seems like it would produce "cleaner" code as far as programmer reading is concerned, but does it affect the program adversely?
    try {
    // code goes here
    } catch (somekindofexception e){
    // print exception e
    } catch (anotherkindofexception e){
    // print exception e
    } // continue for all possible exceptions

    bolivartech wrote:
    I was mistaken it looks like the particular function I was thinking of throws 3 kinds of RuntimeExceptions, but the same idea applies right?
    try {
    } catch (RuntimeException e) {
    System.err.println("Caught RuntimeException: " +  e.getMessage());
    Yes, you can do that if you want to handle all of them the same.
    However, if you want to handle different exceptions differently, you'd catch those specific exceptions, rather than the parent exception type. This is a separate issue from whether you have one big try or lots of little trys.
    NOTE HOWEVER THAT YOU SHOULD NOT CATCH RuntimeException OR ITS DESCENDANTS. RuntimeException indicates an error in your code. Catching it is usually pointless, because you can't recover from it, and trying to continue on will probably lead to corrupt results at best.

  • Surround With Try/Catch : comments issue

    hi
    Please consider this code:
         public static void main(String[] pArguments)
              FileInputStream vFileInputStream = new FileInputStream("someFile.txt");
              // some comments, e.g. several lines of commented code (that might be uncommented later)
         }It is possible to have JDeveloper "Surround With Try/Catch" this, but that results in this code:
         public static void main(String[] pArguments)
              FileInputStream vFileInputStream;
              // some comments, e.g. several lines of commented code (that might be uncommented later)
              try
                   vFileInputStream = new FileInputStream("someFile.txt");
              catch (FileNotFoundException e)
                   // TODO
         }Note that the declaration is before the comments and the try block starts after the comments.
    Is this intentional behaviour? I would prefer to leave the comments where they are, after the (modified) code.
    many thanks
    Jan Vervecken

    Thanks for your reply John.
    I tried the right-click "Surround With..." > "try-catch" approach you suggest, and I get this code:
         public static void main(String[] pArguments)
              try
                   FileInputStream vFileInputStream = new FileInputStream("someFile.txt");
              catch (FileNotFoundException e)
              // some comments, e.g. several lines of commented code (that might be uncommented later)
    }Indeed, the try-block starts before the comments.
    There is another difference with this approach, the declaration is not separated from the assignment.
    Next ... I'll try to remember which approach give which result. :)
    regards
    Jan

  • 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

  • Issue in deploying Service Bus projects using maven

    Hi, I am following the following documentation for deploying service bus projects to my OSB server. http://docs.oracle.com/middleware/1213/core/MAVEN/osb_maven_project.htm#MAVEN8973 I was able to issue mvn package as described in documentation and al

  • Info record no is not appearing in PR Source supply for MRP generated PR

    Hi, I have a material ,I have naintained inforecord & source list .when i am trying create PR with source determination tick ,system is adopting Inforecord no in PR source of supply tab.But if you create PR through MRP ,system is picking only fixed v

  • Should I use an existing usb driver or should I create my own?

    We are developing a custom piece of hardware that uses a TI6250 chip to provide an USB communication channel. I read through the web reference http://zone.ni.com/devzone/conceptd.nsf/webmain/67​92BAB18242082786256DD7006B6416?opendocument that seems t

  • Goods Issue Internal Order using MIGO

    Dear All, I want to do Goods Issue Internal Order using MIGO, but then an error message popup says "Order xxx not found or not permitted for goods movement" When i do the Goods Issue using MB1A, the transaction run well, So why MIGO transaction canno

  • Yup im that bad at this

    simply how do i delete a project its cracking me up