Try/Return/Catch question

The tutorial says no code is allowed between try and catch blocks, but one of the examples given has a return statement between try and catch blocks.
Why is this ( [one of the answers from the tutorial|http://java.sun.com/docs/books/tutorial/essential/exceptions/QandE/answers.html] ) OK?
public static void cat(File file) {
RandomAccessFile input = null;
String line = null;
try {
input = new RandomAccessFile(file, "r");
while ((line = input.readLine()) != null) {
System.out.println(line);
return; //<--- Why is this code legal?
} catch(FileNotFoundException fnf) {
System.err.format("File: %s not found%n", file);
} catch(IOException e) {
System.err.println(e.toString());
} finally {
if (input != null) {
try {
input.close();
} catch(IOException io) {
Just want to understand the unstated exception to these cases.
Thanks,
David Yorke
FNG

You're reading it wrong.
try {
  input = new RandomAccessFile(file, "r");
  while ((line = input.readLine()) != null) {
    System.out.println(line);
  } // end of while loop
  return; //<--- Why is this code legal?
  // legal because it's still inside the try block
}  // end of try block
catch(FileNotFoundException fnf) {
  System.err.format("File: %s not found%n", file);
catch(IOException e) {
  System.err.println(e.toString());
finally {
  if (input != null) {
    try {
      input.close();
    catch(IOException io) {
}

Similar Messages

  • Try - catch question..

    hello..
    i was wondering if i can use a try-block and catch a built in exception without explicitly throwing the exception..
    example:
    try{
    foo[5] = 'A';
    catch (IndexOutOfBoundsException e)
    { blah blah
    is this possible w/o throwing the IndexOut... exception in the try statement?

    You can only catch those exceptions that are (or could be) thrown. The reason your code snippet works is that the exception you're catching is a subclass of RuntimeException. You can always catch any RuntimeException and the compiler will OK it, and you don't have to declare them as being thrown either. If you try to catch an Exception that isn't a RuntimeException (like java.lang.Exception) and isn't thrown, you'll get a compile error. That said, I agree that this isn't the way to do it here.

  • Repost as question for points: What did I do wrong? (Try and Catch program)

    This has to be a try and catch program.
    This is the given output sample:
    OUTPUT SAMPLE #2 for input.txt: 12345 222256 -3 123 -56784 555557 6345678 x x x 81234 121212 x x 123434 x x 1009098 2099
    Please input the name of the file to be opened: input.txt
    For number 12345 the sum of digits is: 15
    For number 222256 the sum of digits is: 19
    Found an integer (-3), but it is negative. Will ignore!
    For number 123 the sum of digits is: 6
    Found an integer (-56784), but it is negative. Will ignore!
    For number 555557 the sum of digits is: 32
    For number 6345678 the sum of digits is: 39
    For number 81234 the sum of digits is: 18
    For number 121212 the sum of digits is: 9
    For number 123434 the sum of digits is: 17
    For number 1009098 the sum of digits is: 27
    For number 2099 the sum of digits is: 20
    Here is what I have so far.
    import java.util.Scanner;
      import java.io.*;// FileNotFoundException
    public class Assignment3b {
      public static void main (String[]args){
        Boolean fileOpened = true; 
        String fileName;
        int n,mod=0,sum=0,t=0;
        Scanner inputFile = new Scanner(System.in);
        System.out.print("Please input the name of the file to be opened: ");
        fileName = inputFile.nextLine();
        System.out.println();
        try {
                inputFile = new Scanner(new File(fileName));
            catch (FileNotFoundException e) {
                System.out.println("--- File Not Found! ---");
                fileOpened = false;
            if (fileOpened) {
              while (inputFile.hasNext()){
                if (inputFile.hasNextInt()){
                  n = inputFile.nextInt();
                  t=n;
                  while(n>0){
                    mod = n % 10;
                    sum = mod + sum;
                    n = n/10;
                  System.out.println ("For number " + t + " the sum of digits is : " + sum);
                  mod = 0;
                  sum = 0;
                  while (n<0) {
                    System.out.println ("Found an integer (" + t + "), but it negative. Will ignore!");
                    inputFile.next();
                    n = inputFile.nextInt();
                else {
                  inputFile.next();
    }Everything seems to work fine until, it is time to deal with negative numbers. How can I fix this. Please put your reply in layman's terms to the best of your ability.
    Thanks and God Bless.

    // COSC 236                                Assignment # 3
    // YOUR NAME: Anson Castelino
    // DUE-DATE:
    // PROGRAM-NAME: Assignment # 3 Prt2
    //import packages
      import java.util.Scanner;
      import java.io.*;// FileNotFoundException
    public class Assignment3b {
      public static void main (String[]args){
        Boolean fileOpened = true; 
        String fileName;
        int n,mod=0,sum=0,t=0;
        Scanner inputFile = new Scanner(System.in);
        System.out.print("Please input the name of the file to be opened: ");
        fileName = inputFile.nextLine();
        System.out.println();
        try {
                inputFile = new Scanner(new File(fileName));
            catch (FileNotFoundException e) {
                System.out.println("--- File Not Found! ---");
                fileOpened = false;
            if (fileOpened) {
              while (inputFile.hasNext()){
                if (inputFile.hasNextInt()){
                  n = inputFile.nextInt();
                  t=n;
                  while(n>0){
                    mod = n % 10;
                    sum = mod + sum;
                    n = n/10;
                  System.out.println ("For number " + t + " the sum of digits is : " + sum);
                  mod = 0;
                  sum = 0;
                  if (n<0) {
                    System.out.println ("Found an integer (" + t + "), but it is negative. Will ignore!");
                    inputFile.next();
                  inputFile.hasNext();
                else {
                  inputFile.next();
    }Updated code.
    current output is as follows:
    Please input the name of the file to be opened: [DrJava Input Box]
    For number 12345 the sum of digits is : 15
    For number 222256 the sum of digits is : 19
    For number -3 the sum of digits is : 0 <-------- this part is not suppose to be here.
    Found an integer (-3), but it is negative. Will ignore!
    For number -56784 the sum of digits is : 0 <-------- this part is not suppose to be here.
    Found an integer (-56784), but it is negative. Will ignore!
    For number 6345678 the sum of digits is : 39
    For number 81234 the sum of digits is : 18
    For number 121212 the sum of digits is : 9
    For number 123434 the sum of digits is : 17
    For number 1009098 the sum of digits is : 27
    For number 2099 the sum of digits is : 20
    >

  • Txt file read in- StringTokenizer- Try Block Catch for errors

    Hello
    So I am having a few issues with a school project. First is with my ReadWithScanner. It does not read in the file giving me a NullPointerException error on the line <Scanner in = new>. I have tried a few other read in files and they do not seem to be working.
    I am also stuck on the logic on the try block catch statement. How does a person set up a �custom� try block that looks for errors like the ones below? I have attempted to start in the commented code.
    The text file has to read in 1000 individual lines of code and are separated by �;� and should be separated into tokens with the StringTokenizer class what I attempted to do below also. Both are mere attempts and need help�
    This is some what of the logic I thought of doing
    1.Read the first line in first with the scanner class
    2.use delimiter separated by �;�
    3.Tokenizer the line into separate tokens- invoiceCode, fName, lName�
    4.Check classes- check Name, check Date, checkPrice, checkPrice, checkGenre, checkShippingDate invoiceCode = "Error Code" checkInvoiceCode(String invoiceCode)checkName(String name), checkPrice(String price), checkGenre(String genre)
    5.Apply the regular expressions to each try block statement
    a.Assign a letter to each error for example if invoice was to short it would be assigned a letter A
    b.If invoice does have the right characters it would be assigned B
    c.If name has to few words it would be assigned D
    d.�
    This is an example of a good field from the text file
    XYG726;Smith,Mr. John M.;29.96;comedy;101008;100604
    Not so good line
    Lu15;Will, Mark;50.00;Science;030305;030807
    The file should then be printed out in the program not to a text file. It only needs to print the invoice number and error code letter assignment.
    If you have any questions feel free to let me know. Thanks for all or any help you have to offer.
    Invoice
    Three upper case letters followed by three digits
    Regular Expression "[A-Z]{3}[0-9]{3}"
    Customer Name
    Should be in the form: last name followed by a <,> optional title (Mrs. Mrs�) then first name optional middle initial Titles must be
    So regular expression something like �[a-z][A-Z]+([A-Z]{1}?[a-z][./})+[a-z][A-Z]�
    Sale Price
    Two decimal digits to the left of the decimal point. The price should not have a leading zero.
    Regular Expression [0-9]{2}*./[0-9]
    Genre
    The genre should only contain lowercase letters. Regular expression �[a-z]�
    ShipDate and Order Date-
    Must be standard dates- MMDDYY. The order date and shipping date has to be after today�s date. Regular expression �[0-9]{2}+[0-9]{2}+[0-9]{2}�
    package Project3;
    import java.util.StringTokenizer;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    import java.io.*;
    import java.util.Scanner;
    public class ReadWithScanner {
    private final File fFile;
    public static void main (String args[]){
    Scanner in = new Scanner(new File("e:\\work_space_java\\Project\\Package3\\movie.txt"));
    Scanner.processLineByLine();
    public ReadWithScanner(String aFileName){
    fFile = new File(aFileName);
    public final void processLineByLine(){
    try {
    //use a Scanner to get each line
    Scanner scanner = new Scanner(fFile);
    while ( scanner.hasNextLine() ){
    processLine( scanner.nextLine() );
    scanner.close();
    catch (IOException ex){
    protected void processLine(String aLine){
    //use a second scanner again to raed the content of each line
    Scanner scanner = new Scanner(aLine);
    scanner.useDelimiter(";");
    if (scanner.hasNext() ){
    //read each file?
    String name = scanner.next();
    String value = scanner.next();
    else {
    scanner.close();
    //Token Names that are seperated
    StringTokenizer st;
    String invoiceCode = st.nextToken();
    String fname = st.nextToken();
    String lname = st.nextToken();
    String price = st.nextToken();
    String genre = st.nextToken();
    String orderDate = st.nextToken();
    String shipDate = st.nextToken();
    String invoiceCode;
    invoiceCode = "A" checkInvoiceCode(String invoiceCode);
    Pattern p = Pattern.compile("[a-z]{6}[A-Z]{6}[0-9]{6}");
    Matcher m = p.matcher(invoiceCode);
    p.matcher(invoiceCode);
    if(m.matches()) {
    System.out.println(invoiceCode);
    else {
    System.out.println ("A");
    try
    invoiceCode = Integer.parseInt(String);
    catch (NumberFormatException e)
    { System.out.println ("B"); System.exit(1); }
    */

    I have made a quite a few updates to my code. Please look it over again. I have also made many comments to help with the logic. Once again if you have any questions please feel free to ask. Sorry about not using the tags before- I was no aware of them. Thanks for the advice sabre150.
    package Project3;
    import java.util.StringTokenizer;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    import java.io.*;
    import java.util.Scanner;
    public class ReadWithScanner {
         private final File fFile;
         public static void main (String args[]){
                   //read in text file from directory currently it can not read the file
                  Scanner in = new Scanner(new File("e:\\work_space_java\\Project\\Package3\\movie.txt"));
                  //Scans each line of the text in
                  Scanner.processLineByLine();
                //assigns new file name to file
                public ReadWithScanner(String aFileName){
                  fFile = new File(aFileName); 
                public final void processLineByLine(){
                  try {
                    //use a Scanner to get each line from the processLineByLine
                    Scanner scanner = new Scanner(fFile);
                    while ( scanner.hasNextLine() ){
                      processLine( scanner.nextLine() );
                    scanner.close();
                  catch (IOException ex){
                protected void processLine(String aLine){
                  //use a second scanner again to read the content of each line
                   //delmiter should then break each line in the text file into seperate "tokens"
                  Scanner scanner = new Scanner(aLine);
                  scanner.useDelimiter(";");
                  if (scanner.hasNext() ){
                       //reads each line from scanner
                    String name = scanner.next();
                  else {
                  scanner.close();
               /*Convert Tokens from Scanner into String Tokenizer with assigment to each variable
                * I am missing something
                * Need to convert each line read from the scanner (name variable) to the String
                * Tokenizer class
              //Tokens names now assigned a varaible
              StringTokenizer st;
              String invoice = st.nextToken();
              String name = st.nextToken();
              String price  = st.nextToken();
              String genre = st.nextToken();
              String orderDate = st.nextToken();
              String shipDate = st.nextToken();
          /*If statments (Try Block Statements?) with Regular Expressions
          * This is where I have the most issues on how to set up
          * "custom" try and block errors trying to match what I have
          * in the regular expressions. 
          * I believe try and catch statements
          * make this easier but I have used 'match' and 'pattern' with if
          * statments.  If try block statements are easier please show!
          * Regular Expressions may not be correct either
           invoice = checkInvoiceCode(invoice);
           //Defined cerita for Inovice are:
           //Error A = Invoice code is too short  
           //Error B = Invoice code does not have the right characters 
           //Error C = Invoice code digits are all zero
           //Checks for error A
           //Has at least six characters
            Pattern invoiceShort = Pattern.compile("{6}");
            Matcher shortInvoice = invoiceShort.matcher(invoice);
            p.matcher(invoiceCode);
            if(m.matches()) {
                 System.out.println(invoice);      
            else {
                 System.out.println ("A");
            //Checks for error B
            //3 Upper Case Letters followed by three numbers,
            Pattern rightChar = Pattern.compile("[A-Z]{3}[0-9]^0{3}");
            Matcher charRight = rightChar.matcher(invoice);
            p.matcher(invoiceCode);
            if(m.matches()) {
                 System.out.println(invoice);
            else {
                     System.out.println ("B");
            //Checks for error C
            //Where the last three digits are not all zeros
            Pattern notZero = Pattern.compile("*{3}^0{3}");
            Matcher ZeroNot = notZero.matcher(invoice);
            p.matcher(invoiceCode);
            if(m.matches()) {
                 System.out.println(invoice); 
                 else {
                     System.out.println ("C");
         //name = checkFullName(name);
         //Error D = Name field has fewer than two words
         //Error E = Name field has more than four words
         //Error F = Name field has no comma
         //Error G = Name field has a bad title 
         //Error H = Name field has a bad initial 
        /*Have a lot more to do...
        * Still need to go through the same if statement or Try Block statements with this data:
        *      String fname = st.nextToken();
              String lname = st.nextToken();
              String price  = st.nextToken();
              String genre = st.nextToken();
              String orderDate = st.nextToken();
              String shipDate = st.nextToken();
        * But for now I would like to see an example of an if statement I could use
        * (if mine is even right) or catch statement- the rest of the project we look
        * for similar certia as defined in the reg exp for invoice
         /*Writes to Report in the Console
         * Prints data into two columns:
         * Invoice Code and Error Type
         //Prints both column Headings
         private void columnHeadings ()
         System.out.println (padL("",5) +
         padL("Invoice",20) +padL("",20)+
         padL("Error Code",40));
         //movie is the name of the text file
         private void printMovie(Movie aReport) {
         System.out.println(aReport.getInvoiceCode()+"\t"+
               aReport.getErrorType()+"\t");
      *This method pads the string start to the length newLength leaving the
      *string left justified and returning the result.
      private String padL (String start, int newLength)
         String result = new String (start);
         while (result.length() <= newLength) result += " ";
         return result;
      } // end padL
       * This method pads the string start to the length newLength leaving the
       * string right justified and returning the result.
      private String padR (String start, int newLength)
         String result = new String (start);
         while (result.length() <= newLength) result = " " + result;
         return result;
    // end padRThanks a lot.

  • Textfields Try and Catch

    Hi All, just a quick question really...
    Was wondering how I would go about checking user inputs into textfields?
    For example if the user enters the number 12 and you're only allowed to enter numbers between 1-10 how could I send a pop up error message to say "You can only enter numbers between 1-10"
    A way I thought about doing this was with a try and catch method, there could be another way of doing this, all other methods appreciated too.
    function captureNumbers(evt:MouseEvent):void {
    try{
    numberSelect.push(Number(number1.text));
    catch{
    if (numberSelect > 10){
    throw new Error("You must choose a number between 1 - 10");
    button1.addEventListener( MouseEvent.MOUSE_UP, captureNumbers);
    This is what ive got so far which doesn't seem to be working...
    Thanks in advance

    public class userBean(String user) {
         // Loads user preferences
         String fname;
         String lname;
         String greeting;
         void public readDB()
              Connection conn = null;
              PreparedStatement pstmt = null;
              ResultSet result = null;
              try {
                   Class.forName("oracle.jdbc.driver.OracleDriver");
              catch (Exception e) { System.out.println("Can't load JDBC driver:" + e); return; }
                   try{
                   conn = DriverManager.getConnection
                       ("jdbc:oracle:thin:@username.domain.com:1521:adm2", "login", "pass");
                   // @machineName:port:SID,   userid,  password d     
                   stmt = conn.prepareStatement("select fname,lname,greeting from people where userid = ?");
                     stmt.setString(1,user);
                     result= stmt.executeQuery();
                     fname = result.getString(1);
                     lname = result.getString(2);
                     stmt.close();
                   catch (Exception e) { System.out.println("Error with JDBC Connection:" + e); return;}          
    }

  • 500 Internal Server Error OracleJSP: code too large for try statement catch

    We have an application which uses JSPs as front end and we are using Struts 1.1. When we run one of the JSP it shows the following error after executing .We are using OCJ4 server having version 9.0.4.0
    500 Internal Server Error
    OracleJSP: oracle.jsp.provider.JspCompileException:
    Errors compiling:E:\oracle\product\10.1.0\AS904\j2ee\home\application-deployments\VAS3006\vas\persistence\_pages\\_Requirement .java
    code too large for try statement catch( Throwable e) { 
    7194
    code too large for try statement catch( Exception clearException) { 
    44
    code too large for try statement try { 
    23
    code too large public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { 
    The JSP/application runs okay on one machine (System Tesing machine)with OCJ4 server having version10.1.2.0 but throughs an error on other machine( Development machine)with OCJ4 server having version9.0.4.0.The question is why it is running on one machine ane giving error on other machine I am aware that there can't be more than 64kB of code between try-catch block .Total size of the generated JSP class in our case is 577KB.
    Is the problem because of different version of Application server OC4J?.Is it any fix for this? Or Can anyone please suggest a work around. Or is there a method by which the JSP generated code is split between different try - catch blocks rather than a single try-catch block.Utlimately We don't know the whether is it a problem with JVM or hardware .
    It would be really helpful if you would provide me with some suggestion and input.
    Regards
    Shyam

    Sir,
    I am aware of the limitations of JVM that it won't allow java code more than 64Kb in method but we are using different versions of Application server .Application is working okay with OC4J application server(10.1.2.0) but gives error on Application server with version 9.0.4.0. Is this a problem with OC4J application server 9.0.4.0. I had gone through the documentation ofOC4J 9.0.4.0.application server but it does not mention about the this bug/fixes.
    Please giude me on the same.
    Regards,Shyam

  • With out try and catch

    with out any try and catch is exception handling is possible in java when doing manupulation with database.
    assume mydatabase is oracle,if i am going to insert a record of a primarykey field, which is already existing.i don't want to put with in try and catch.This is my case.if u have the answer for this please mail me.
    thanks
    rajan

    assume mydatabase is oracle,if i am going to insert a
    record of a primarykey field, which is already existing.
    i don't want to put with in try and catch.why not? i thought the fact that checked exceptions get thrown from methods is a good thing, since you're forced either to deal with the fault immediately, or throw to the next level up, possibly transformed into an application-level exception. if methods were to simply return method-specific error codes, nothing forces anything in the program to deal with errors in a reasonable manner. not that exceptions force sensible handling of the fault--but they do force recognition of the fault.
    what alternative do you desire?
    --p

  • Remediate to content slide; return to question; then continue on - using Captivate 8

    Using Captivate 8, I’m trying to remediate from a Knowledge Check question slide back to a content slide, then back to the KC question to try again, and then continue on from there.  On my first instance, this works fine.  However, the problems began on the second instance and continue on each instance thereafter. The settings on the KC question slides are all the same with the exception of which slide each jumps to for remediation.  I don't understand why it works the first time, but doesn’t work after that. On the second instance the question jumps back to the content slide, but then skips any subsequent slides.   Anyone had a similar experience?  Know of a workaround or what I might be doing wrong?
    FYI, I'm using he E-Learning Uncovered Adobe Captivate 8 book by Elkins, Pinder, and Slade as a reference, and it clearly describes how to do this on page 183, "Remediation back to Content Slides - If students get a question wrong, you can branch back to one or several slides where the content was taught and then return them back to the quiz to retry the question.  To add remediation branching:  1) in the last attempt field on the question, set a Jump to Slide action to the first slide with the content.  2) On the last slide with the content, add a return to Quiz action on the slide's next button.  On the content slide, the Next button with the Return to Quiz action executes a Continue action under normal circumstances, but returns students to the quiz if that's where they came from."
    Please see content map below:
    Content
    Mapping:
    Slide 1 – Content
    Slide 2 – Content
    Slide 3 – Content
    Slide 4 – Content
    Slide 5 – Content
    Slide 6 – Content
    Slide 7 – Content
    Slide 8 – Content
    Slide 9 – Knowledge Check Question -Remediates back to slide 5 if user misses two attempts to answer; slide 5 returns user to Slide 9 for one last try at question, then advances to Slide 10 (works perfectly)
    Slide 11 – Content (here’s the first problem; on click, slide 11 jumps to the Knowledge Check Question on Slide 13, skipping slide 12)
    Slide 12 – Content
    Slide 13 – Knowledge Check Question that remediates back to slide 11 if user misses on 2 attempts to answer; slide 11 should return user here for one last try at question, then advance to Slide 14
    Slide14 – Content
    Slide 15 – Content (here’s the second problem; on click, slide 15 jumps to the Knowledge Check Question on Slide 19, skipping slides 16, 17, and 18)
    Slide 16 – Content
    Slide 17 – Content
    Slide 18 – Content

    I've tried contacting Adobe, too, but with no clear resolution yet.  One suggestion they gave me was to put the slide you are remediating back to right before the question slide.  However, if you can only remediate back to the slide immediately before the question slide, that limits this functionality severely.  My solution has been to remediate to a duplicate, but separate content slide using buttons rather than quiz logic.  Cumbersome, but it works.
          From: camelothome <[email protected]>
    To: Anne Kimmitt <[email protected]>
    Sent: Friday, May 15, 2015 1:41 PM
    Subject:  Remediate to content slide; return to question; then continue on - using Captivate 8
    Remediate to content slide; return to question; then continue on - using Captivate 8
    created by camelothome in Quizzing/LMS - View the full discussionI have the same problem with my project.  If the player detects that a quiz has begun, it sees it as in quiz scope.  Thus, when it encounters the next slide after the quiz slides that has "Return to Quiz" as the Exit Action, it instead goes to the next set of quiz questions and skips a bunch of content slides. I don't know where I read it, but I thought that if the slide was being visited for the first time, and did not come from a quiz, the "Return to Quiz" would have no effect and it would continue to the next content slide.  Perhaps I am wrong, but I thought that was the correct behavior. I've attempted to get help from Adobe, but the operator was not very helpful.  He wanted me to upload my file using wetransfer.com but gave me an invalid e-mail address.  Since that was the second attempt to get help, I gave up on Adobe Support.  Although I get the suggest above, it's a pain, especially since I don't have buttons on the content slides.  I have the player just playing with the playbar available for pauses.  So, now I have to create some sort of workaround using variables, but I don't think this is how it's supposed to work.  In fact, I'm not sure what I did yesterday that caused it to work correctly for a while, but I'm pretty sure I didn't change anything related to this.  Of course, then it stopped working. I find Adobe Captivate to be pretty buggy and it's put me way behind in delivering a product to my client.  I'm very frustrated. If the reply above answers your question, please take a moment to mark this answer as correct by visiting: https://forums.adobe.com/message/7548938#7548938 and clicking ‘Correct’ below the answer Replies to this message go to everyone subscribed to this thread, not directly to the person who posted the message. To post a reply, either reply to this email or visit the message page: Please note that the Adobe Forums do not accept email attachments. If you want to embed an image in your message please visit the thread in the forum and click the camera icon: https://forums.adobe.com/message/7548938#7548938 To unsubscribe from this thread, please visit the message page at , click "Following" at the top right, & "Stop Following"  Start a new discussion in Quizzing/LMS by email or at Adobe Community For more information about maintaining your forum email notifications please go to https://forums.adobe.com/thread/1516624.

  • Help in try ans catch

    Hi,
    i do method that get input and return table and i wont to use try & catch if the table i receive is empty how i can do that exception library?
    Regards

    if within ur method no exception is raised then no need to use try..catch..entry block.
    After the method call u can directly check the contents of the return table. If it contains value then do further processing otherwise do the error handling.
    Regards,
    Joy.

  • TRY..catch block in a loop.

    Hi Epxerts,
    Can i use loop endloop for the following TRY..CATCH block as i need to send multiple records
    LOOP.
    TRY.
      Assign row
        it_prxstruc-MT_table_EXTRACT-record-row = wa_area1. --> one record of
        CALL METHOD prxy->execute_asynchronous
          EXPORTING
            output = it_prxstruc --> 1 record.
        COMMIT WORK
      CATCH cx_ai_system_fault .
        DATA fault TYPE REF TO cx_ai_system_fault .
        CREATE OBJECT fault.
        WRITE :/ fault->errortext.
    ENDTRY.
    ENDLOOP.
    Please suggest accordingly.
    Thanks
    Dany

    Try-Endtry specifies the territory of exception that catch is going to handle. Do it this way..
    TRY.
    LOOP.
    Assign row
    it_prxstruc-MT_table_EXTRACT-record-row = wa_area1. --> one record of
    CALL METHOD prxy->execute_asynchronous
    EXPORTING
    output = it_prxstruc --> 1 record.
    COMMIT WORK
    ENDLOOP.
    CATCH cx_ai_system_fault .
    DATA fault TYPE REF TO cx_ai_system_fault .
    CREATE OBJECT fault.
    WRITE :/ fault->errortext.
    ENDTRY.
    G@urav.

  • Mapping Try n Catch

    Can any one tell me,
    How to use Try n Catch in Mapping?
    -naveen

    Hi Naveen,
    Look at the java code in the thread..
    user defined function in java for message mapping
    cheers,
    Prashanth
    P.S : Please mark helpful answers

  • Is there try and catch in oracle query ?

    hi
    is there try and catch in oracle query ?
    try
    do some update
    catch
    if there was error go to here
    }

    >
    is there try and catch in oracle query ?
    >
    Yes - except it uses BEGIN --- EXCEPTION --- END where BEGIN replaces the try and EXCEPTION replaces the catch.
    BEGIN
    -- Calculation might cause division-by-zero error.
       pe_ratio := stock_price / net_earnings;
       dbms_output.put_line('Price/earnings ratio = ' || pe_ratio);
    EXCEPTION  -- exception handlers begin
    -- Only one of the WHEN blocks is executed.
       WHEN ZERO_DIVIDE THEN  -- handles 'division by zero' error
          dbms_output.put_line('Company must have had zero earnings.');
          pe_ratio := null;
       WHEN OTHERS THEN  -- handles all other errors
          dbms_output.put_line('Some other kind of error occurred.');
          pe_ratio := null;
    END;  -- exception handlers and block end here
    /The multiple WHEN conditions correspond to using multiple 'catch' statements in Java.

  • Try and Catch don't work on powershell module

    Hi everyone,
    i'm tring to create a module with a try and catch, but when i call it, the block of expetion doesn't work as i expect, while if i use the code as a function only it works...
    Here the code
    function global:Process{
    param([string]$Process)
    ######################################MAIL################################
    function global:SendMail(){
    param([string]$Services)
    $Dest="xxx"
    $smtpServer = "xxx"
    $msg = new-object Net.Mail.MailMessage
    $smtp = new-object Net.Mail.SmtpClient($smtpServer)
    $msg.From = "xxx"
    $msg.To.Add($Dest)
    $msg.Subject = "Notification about $Services activity"
    $msg.Body = "xxxx"
    $smtp.Send($msg)
    switch($Process){
    "DSP"{
    if((Get-Service Fax | ForEach-Object {$_.Status}) -eq "Stopped"){
    try
    start-service Fax -ea Stop
    catch
    if ( $error[0].Exception -match "Microsoft.PowerShell.Commands.ServiceCommandException")
    $error[0].Exception | Out-File C:\log.txt
    $SendMail $Process
    elseif((Get-Service Fax | ForEach-Object {$_.Status}) -eq "Running"){
    Stop-Service Fax}
    Export-ModuleMember -Function Process
    Could you help me? Thanks so much
    Cristian

    Hello,
    You should ask in the
    Windows PowerShell forum.
    Karl
    When you see answers and helpful posts, please click Vote As Helpful, Propose As Answer, and/or Mark As Answer.
    My Blog: Unlock PowerShell
    My Book:
    Windows PowerShell 2.0 Bible
    My E-mail: -join ('6F6C646B61726C406F75746C6F6F6B2E636F6D'-split'(?<=\G.{2})'|%{if($_){[char][int]"0x$_"}})

  • Using  try{}..Catch()

    Hi ,
    Is there any way so that i can use 'try{} without catch() and finally{}.
    Thanks

    > Is there any way so that i can use 'try{} without
    catch() and finally{}.
    One would only use a try{} block in order to also use a catch/finally block. A try{} block doesn't do anything by itself per se; it sounds like you might be looking for a way to add the Exception to the method signature. Is this the case?
    The Java� Tutorial - Lesson: Handling Errors with Exceptions

  • Try to catch the 'long' operation ...

    Hello,
    With the following SQL statement, I try to catch the remaining time of a long operation :
    select sid,totalwork, sofar, time_remaining, ELAPSED_SECONDS
    from v$session_longops
    where totalwork > sofar;
    The aim is to use it to warn the user when he does a long search.
    But i can't find a way to isolate one long operation concerning one user/action.
    The problem is that multiple person login into the same user (not really good, I know but ...) and with a user, I can't get his SID ...
    Any help willbe gladly appreciated.
    Miguel

    I finnaly found it! ;-)
    select sid,serial# from v$session where audsid=userenv('SESSIONID');

Maybe you are looking for

  • Front Row Slideshow Music Problem

    Hello: I have been unable to change the Photo Slideshow music in Front Row. I go into iPhoto, select SlideShow and select my music, but it does not seem to save it to Front Row. I've even tried making my selections as "default" but it doesn't work. I

  • Follow on doc(PREQ) not created in teh  backend

    Hi All,   Need some urgent help...We are runnin on SRM 5.0 n the Classic scneario....   When we order the SC,The  backend  doc  is  not created..In the follow on documents...we just get the status  as  Approved....The workflow is in status  completed

  • Genius in iPod classic 80GB ? Is it working?

    Hi everyone I am new here with my first 'issue' of my ipod. I always thought I can use geniuas with my ipod classic until I actually started to using it. I cannot see any option called genius in my ipod classic 80GB. Is something wrong with my ipod o

  • Itunes restarted after computer update and lost every thing

    Hello, I recently updated my computer ( macbook with a mac os x 10.5.8 ) . one of the updates was for the itunes. after i restarted every thing somthing went wrong with my itunes and now it looks like i have itunes 8 . all my playlists are gone and a

  • Need tutorial on paint

    I am filming a sequence in a gymnasium using spotlights and I have an exit sign in the background that I woould like to remove.Could some one direct me to a tutorial thst would give me step by step info. to remove the sign? Can you use paintbrush to