Java try-catch doubt

Hi all,
I have one doubt regarding the try catch mechanism. In my class I have a try catch block. And in my catch block i am doing some db(insert) operations. Is it possible for me to add another try catch to this perticular catch block?
I have given a sample what i am looking for below.
eg: try{
}// end of try
catch{
try{
}// end of try in catch
catch{
}//end of catch in catch
}end of main catch
Please give some suggestions on this.
Thanks and regards,
Jithesh PM

JitheshOnJava wrote:
Hi all,
I have one doubt regarding the try catch mechanism. In my class I have a try catch block. And in my catch block i am doing some db(insert) operations. Is it possible for me to add another try catch to this perticular catch block? Yes. Did you try it?

Similar Messages

  • Try - catch doubt

    I have a set of file IO operations, like file opening, buffering, writing etc. . Can I enclose everything in one try-catch or have use separate for each file IO operations

    If any one of them will cause your method to "fail", then use a single try block.
    You could have tried this for yourself. Ie written the codr this way and seen if it compiles without error. Even tested it with IOExceptions that are easy to cause (like nonexistant files or files you don't have permission to write to etc).
    Sometimes there might be action you can do to recover from an exception. In that case one particular step might use its own try block. Note: you can nest try blocks, also.

  • "catch is unreachable" compiler error with java try/catch statement

    I'm receiving a compiler error, "catch is unreachable", with the following code. I'm calling a method, SendMail(), which can throw two possible exceptions. I thought that the catch statements executed in order, and the first one that is caught will execute? Is their a change with J2SE 1.5 compiler? I don't want to use a generic Exception, because I want to handle the specific exceptions. Any suggestions how to fix? Thanks
    try {
    SendMail(....);
    } catch (MessagingException e1) {
    logger.fine(e1.toString());
    } catch (AddressException e2) {
    logger.fine(e2.toString());
    public String SendMail(....) throws AddressException,
    MessagingException {....                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    I found the problem:
    "A catch block handles exceptions that match its exception type (parameter) and exception types that are subclasses of its exception type (parameter). Only the first catch block that handles a particular exception type will execute, so the most specific exception type should come first. You may get a catch is unreachable syntax error if your catch blocks do not follow this order."
    If I switch the order of the catch exceptions the compiler error goes away.
    thanks

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

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

  • String:///index_jsp.java:204: 'catch' without 'try'

    I was getting this error when i had a proper try-catch block.
    Now, i removed the try catch block entirely & there is no word catch in my whole program, still it gives me this error
    Please help

    string:///index_jsp.java:204: 'catch' without 'try' this means. you mis place calibrace i.e { } . so correct it.
    proper opening and closing calibrace i.e { }. should be do do avoid this error.
    method()
    try
    catch(some exception)
    catch some things
    before going to post any problem means: you must read this.
    https://forums.oracle.com/forums/ann.jspa?annID=56

  • How to use Try Catch Block in ABAP Like JAVA

    Hi Experts,
       I am using BAPI to post MIGO in one of my application. If the MIGO is successfully gets posted then BAPI returns no message, but if there is some error in posting then it returns an error message. Now I want to print that error message in catch block by calling method RAISE_ERROR_MESSAGE. How to use try catch block in ABAP. Please suggest with example.
    Thanks and Regards.
    Vaibhav Tiwari.

    Hi Vaibhav
    You may not catch exceptions returned by function module using try endtry block.
    It works well with the exception returned by methods.
    In case of function modules or BAPI what u can do is to check sy-subrc returned and give message accordingly. If it returns a structure like bapireturn then display message returned.
    in case of exception returned by a method,  do it like this...
    data: excep type cx_root.
    data: v_str type string.
    try.
    *any method call or division by zero (for ex)
    catch cx_root into excep.
    endtry.
    if  excep is not initial.
    CALL METHOD   excep->if_message~get_text
      receiving
        RESULT = v_str.
    endif.
    *display the value returned in v_str on screen

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

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

  • Some simple question , but i dont know...try & catch ..

    Hi i was working on a media player and i've faced some problems...like what exactly does the try&catch do ??
    and in the Player class what the realize() and prefetch do ??
    Thank you in advance..
    Mulham Haffar

    If you are in doubt when or what exceptions to catch, use the java compiler as your guide. You will get compile time errors that clearly name the exception you have to catch with the line of code that could cause the exception/error. Then do the following:
    try {
      // the code that could throw the exception
    } catch ([the-name-exception] e) {
      e.printStackTrace();
      // or do something else relevant here - this code gets executed when the exception is thrown
    } finally {
      // this is an optional block that is always executed before returning from the method (even if there was an exception thrown - do stuff like closing resources here
    }where [the-name-exception] is the exception class I mentioned earlier.
    You can also declare a method to throw the exception if you don't want to catch it. Just use the keyword "throws" followed by the class name of the exception. Then any place where you call the method will have to catch the exception.
    You can also find out what exceptions are being thrown by looking in the JavaDocs. There is plenty more, but that is what you will need to get your program compiling.

  • 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 accept 2 strings in a class with try catch method..help!!

    the program below will accept two strings and compare str1 and str2 if equal. this program uses functions. can any one help me with this?
    import java.io.*;
    public class StrCompare {
         private BufferedReader takyoin = null;
         //private BufferedReader intakyo = null;
         * @param args
         public StrCompare(){
              takyoin = new BufferedReader(new InputStreamReader(System.in));
              //intakyo = new BufferedReader(new InputStreamReader(System.in));
         public String UserInput(){
         public static void main(String[] args) {
              // TODO Auto-generated method stub
    }

    What are you talking about? There is no such thing as "try-catch-methods", and there are no functions but methods.
    Strings by the way have their own means of comparision. Apart from that: do your own homework.

  • Try/catch and 'cannot resolve symbol'

    I am relatively new to java programming and something has me puzzled...
    Why do I get a 'cannot resolve symbol' message when I include a variable definition in a try/catch section. When I put it/them before the 'try' statement it compiles as expected. How are statements inside a try compiled differently than those outside?
    try {
        StringBuffer pageBuffer = new StringBuffer();
        String inputLine;
        BufferedReader in = new BufferedReader(
           new InputStreamReader( theURL.openStream() ) );
        while ((inputLine = in.readLine()) != null) {
             System.out.println(inputLine);
            pageBuffer.append(inputLine);
        in.close();
    } catch (Exception ignored) {}C:\Projects\WebExplorer\PageVisitor.java:142: cannot resolve symbol
    symbol : variable pageBuffer
    location: class PageVisitor
         return pageBuffer.toString();
    Paul

    A try block is just like any other block delimited by {...} in that all variables declared inside it are local to that block. I.e. they are not visible or usable anywhere outside it. Your pageBuffer variable, for example, is a local variable that can only be used inside the try-block in which it is declared.
    Your obvious solution, knowing that, is to declare the variables outside the try and catch blocks. Remember to initialize them (even to null), otherwise the compiler will complain about variables that may not have been initialized.

  • 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 issue - "cannot find symbol - class InputMismatchExeption"

    I'm still learning try/catch but from what i've read online and in the class library it looks right...i'm not sure why it won't compile.
    try {
                    do {
                        System.out.print("Enter command (1-5): ");
                        selection = scan.nextInt();
                        if (selection < 1 || selection > 5) {
                            System.out.print("Illegal command number.");
                            System.out.println("The available commands are:");
                            System.out.println("\t1. Add new entry to the address book.");
                            System.out.println("\t2. Delete existing entry from address book entries.");
                            System.out.println("\t3. Print out all address book entries.");
                            System.out.println("\t4. Search records for a certain pattern.");
                            System.out.println("\t5. Quit the Application.");
                    while (selection < 1 || selection > 5);
                //this does not work!!!!!!
                catch( InputMismatchException ime ){
                    System.out.println("Illegal command.");
                }

    I have
    import.java.io.*;at the beginning before i declare my class. I'm not sure abotu the second thing you said, could you elaborate?
    I'm sorry, I'm still new at java.
    edit: yeah, I didn't import java.util.... hides in shame
    Do i still have to import util.Scanner or will that import automatically when i import util.*
    Message was edited by:
    Cymae

Maybe you are looking for