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;}          
}

Similar Messages

  • 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

  • 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$_"}})

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

  • How the try and catch blocks work?

    For the following section of code from the class QueueInheritanceTest...how the try and catch blocks work?
    The Class...
    public class QueueInheritance extends List {
    public QueueInheritance() { super( "queue" ); }
    public void enqueue( Object o )
    { insertAtBack( o ); }
    public Object dequeue()
    throws EmptyListException { return removeFromFront(); }
    public boolean isEmpty() { return super.isEmpty(); }
    public void print() { super.print(); }
    Testing...
    public class QueueInheritanceTest {
    public static void main( String args[] ){
    QueueInheritance objQueue = new QueueInheritance();
    // Create objects to store in the queue
    Boolean b = Boolean.TRUE;
    Character c = new Character( '$' );
    Integer i = new Integer( 34567 );
    String s = "hello";
    // Use the enqueue method
    objQueue.enqueue( b );
    objQueue.enqueue( c );
    objQueue.enqueue( i );
    objQueue.enqueue( s );
    objQueue.print();
    // Use the dequeue method
    Object removedObj = null;
    try { while ( true ) {
    removedObj = objQueue.dequeue();
    System.out.println(removedObj.toString()+" dequeued" );
    objQueue.print();
    catch ( EmptyListException e ) {
    System.err.println( "\n" + e.toString() );

    If you want a basic introduction to try/catch blocks, read any introductory text or the tutorials on this site.
    Here are some:
    Sun's basic Java tutorial
    Sun's New To Java Center.
    JavaRanch. To quote the tagline on their homepage: "a friendly place for Java greenhorns."
    In terms of this particular case, it looks like the code is using an exception being thrown to get out of a loop. IMHO that's bad design -- exceptions should be used for exceptional circumstances, and if you use it to get out of a loop, then you're certain it's going to happen, and that means that it's not exceptional.
    When you post code, please wrap it in  tags so it's legible.

  • Stack that implements try and catch problem

    Hi guys, i'm pretty new to java (and programming all together) , have a difficulties with this calculator i'm working on.
    I've got a stack which holds for instance 5 + 6 * 2
    which equals 17. What i have is:
    Stack<String> expression = new Stack<String>(
    while(expression.size() >= 2){
    String X = new String();
    String Y = new String();
    X = expression.pop();
    System.out.println("popin stack"+X); //debuggin purposes
    try {double x = Double.parseDouble(X);  
                   if (X.equals('+')) {
                       Y = expression.pop();
                       double y = Double.parseDouble(Y);
                       String result = Operation.PLUS.eval(x,y);
                       System.out.println(result);
                       expression.push(result);
    else if (X.equals('-')) {
    Y = expression.pop();
    double y = Double.parseDouble(Y);
    String result = Operation.MINUS.eval(x,y);
    System.out.println(result);
    expression.push(result);
    else if (X.equals('/')) {
    Y = expression.pop();
    double y = Double.parseDouble(Y);
    String result = Operation.DIVIDE.eval(x,y);
    System.out.println(result);
    expression.push(result);
    else {
    Y = expression.pop();
    double y = Double.parseDouble(Y);
    String result = Operation.TIMES.eval(x,y);
    System.out.println(result);
    expression.push(result);
    catch () { }
    My idea behinde this was i'd used the try statement
    to prevent the element being converted to a double if it isn't a String which this can be done to i.e any integer. I'm not sure if i've gone about this right. And have not idea of what i'm suppose to be catchin i.e the throwable?. Any input/direction would be great, thanks.

    Hi guys, i'm pretty new to java (and programming all together) , have a difficulties with this calculator i'm working on.
    I've got a stack which holds for instance 5 + 6 * 2
    which equals 17. What i have is:
    Stack<String> expression = new Stack<String>(
    while(expression.size() >= 2){
         String X = new String();
         String Y = new String();
         X = expression.pop();
         System.out.println("popin stack"+X); //debuggin purposes
         try {double x = Double.parseDouble(X);
         if (X.equals('+')) {
               Y = expression.pop();
               double y = Double.parseDouble(Y);
               String result = Operation.PLUS.eval(x,y);
               System.out.println(result);
               expression.push(result);
          else if (X.equals('-')) {
               Y = expression.pop();
               double y = Double.parseDouble(Y);
               String result = Operation.MINUS.eval(x,y);
               System.out.println(result);
               expression.push(result);
         else if (X.equals('/')) {
               Y = expression.pop();
               double y = Double.parseDouble(Y);
               String result = Operation.DIVIDE.eval(x,y);
               System.out.println(result);
               expression.push(result);
         else {
               Y = expression.pop();
               double y = Double.parseDouble(Y);
               String result = Operation.TIMES.eval(x,y);
               System.out.println(result);
               expression.push(result);
         catch () { }
    } My idea behinde this was i'd used the try statement
    to prevent the element being converted to a double if it isn't a String which this can be done to i.e any integer. I'm not sure if i've gone about this right. And have not idea of what i'm suppose to be catchin i.e the throwable?. Any input/direction would be great, thanks.
    Edited by: javaUser on Dec 30, 2007 5:59 PM

  • Help with try and catch

    I know I posted this quesiton earlier,but I am sitll having problems. In the following code, the exception IS caught if the user enters a String instead of a Int. But the Exception is NOT caught if the user enters
    the "Enter" key.
                do
                              flag=false;
                     //set the quantity to user input                                                   
                     System.out.print("Enter the quantity:");
                     try
                       amount = input.nextInt();
                          if (amount > 0)  //executes when amount is less then or equal to zero
                             flag=false; 
                          } //end of if
                          else
                               System.out.println("You must enter a positive quantity");
                                              flag=true;
                     }  //end of try
                     catch (Exception e)
                                      input.nextLine();
                                      System.out.println("You must enter a number");
                                      flag=true;
                }while(flag==true);  //end of do while
                          

    nextInt won't read "just the enter key"... it blocks until reads "something".
    Try something like this instead...
    Note: java.io.Console is new in 1.6
    package krc.utilz.io;
    // usage:
    // import krc.utilz.io.Console;
    // String name = Console.readLine("Enter your name : ");
    // while ( (score=Console.readInteger("Enter a score between 0 and 100 (enter to quit) : ", 0, 100, -1)) != 1) { ... }
    import java.util.Date;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    public abstract class Console
      private static final java.io.Console theConsole = System.console();
      private static final DateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy");
      public static String readLine(String prompt) {
        while(true) {
          try {
            System.out.print(prompt);
            return theConsole.readLine();
          } catch (Exception e) {
            System.out.println("Oops: "+e);
      public static Date readDate(String prompt) {
        while(true) {
          try {
            String response = readWord(prompt+" (dd/mm/yyyy) : ");
            return dateFormatter.parse(response);
          } catch (Exception e) {
            System.out.println("Oops: "+e);
      public static String readWord(String prompt) {
        String response = null;
        while(true) {
          try {
            response = readLine(prompt);
            if( response!=null && response.length()>0 && response.indexOf(' ')<0 ) break;
            System.out.println("A single word is required. No spaces.");
          } catch (Exception e) {
            System.out.println("Oops: "+e);
        return(response);
      public static char readLetter(String prompt) {
        char c = '\0';
        while(true) {
          try {
            String response = readLine(prompt);
            if ( response!=null && response.length()>0 ) {
              c = response.charAt(0);
              if(Character.     isLetter(c)) break;
            System.out.println("A letter (A through Z) is required. Upper or lower case.");
          } catch (Exception e) {
            System.out.println("Oops: "+e);
        return(c);
      public static int readInteger(String prompt) {
        int i = 0;
        String response = null;
        while(true) {
          try {
            response = readLine(prompt);
            if ( response!=null && response.length()>0 ) {
              i = Integer.parseInt(response);
              break;
            System.out.println("An integer is required.");
          } catch (NumberFormatException e) {
            System.out.println("\""+response+"\" cannot be interpreted as an integer!");
          } catch (Exception e) {
            System.out.println("Oops: "+e);
        return(i);
      public static int readInteger(String prompt, int lowerBound, int upperBound) {
        int i = 0;
        while(true) {
          i = readInteger(prompt);
          if ( i>=lowerBound && i<=upperBound ) break;
          System.out.println("An integer between "+lowerBound+" and "+upperBound+" (inclusive) is required.");
        return(i);
      public static int readInteger(String prompt, int defualt) {
        int i = 0;
        String response = null;
        while(true) {
          try {
            response = readLine(prompt);
            return (response!=null && response.trim().length()>0
              ? Integer.parseInt(response)
              : defualt
          } catch (NumberFormatException e) {
            System.out.println("\""+response+"\" cannot be interpreted as an integer!");
          } catch (Exception e) {
            System.out.println("Oops: "+e);
      public static int readInteger(String prompt, int lowerBound, int upperBound, int defualt) {
        int i = 0;
        while(true) {
          i = readInteger(prompt, defualt);
          if ( i==defualt || i>=lowerBound && i<=upperBound ) break;
          System.out.println("An integer between "+lowerBound+" and "+upperBound+" (inclusive) is required.");
        return(i);
      public static double readDouble(String prompt) {
        double d = 0;
        String response = null;
        while(true) {
          try {
            response = readLine(prompt);
            if ( response!=null && response.length()>0 ) {
              d = Double.parseDouble(response);
              break;
            System.out.println("A number is required.");
          } catch (NumberFormatException e) {
            System.out.println("\""+response+"\" cannot be interpreted as a number!");
          } catch (Exception e) {
            System.out.println("Oops: "+e);
        return(d);
      public static double readDouble(String prompt, double lowerBound, double upperBound) {
        while(true) {
          double d = readDouble(prompt);
          if ( d>=lowerBound && d<=upperBound ) return(d);
          System.out.println("A number between "+lowerBound+" and "+upperBound+" (inclusive) is required.");
      public static boolean readBoolean(String prompt) {
        while(true) {
          try {
            String response = readWord(prompt+" (Y/N) : ");
            return response.trim().equalsIgnoreCase("Y");
          } catch (Exception e) {
            System.out.println("Oops: "+e);
    }

  • Test and trust Class.isInstance or try and catch Class.cast ?

    I found this related thread, with no answer to my question.
    In the below code, there is a certain level of redundancy in that I am checking that I can do the Class.cast() prior to doing it, via Class.isInstance().
    I can either omit the isInstance() check and just count on cast() throwing an exception, or I can ignore the ClassCastException (do nothing in the catch block, as shown below).
    Which is better? Is it faster if I just omit the instance check and let cast() detect the errors? Is there a style convention here?
        protected <T extends ParentClass> List<T> getItemsOfType(Class<T> clazz){
            List<T> retval = new ArrayList<T>();
            for(ParentClass t : items.values()){
                if(clazz.isInstance(t)){
                    try{
                        retval.add(clazz.cast(t));
                    catch(ClassCastException cce){
                        // should never happen
        }Thanks for your time

    Derrick.Rice wrote:
    I found this related thread, with no answer to my question.
    In the below code, there is a certain level of redundancy in that I am checking that I can do the Class.cast() prior to doing it, via Class.isInstance().
    I can either omit the isInstance() check and just count on cast() throwing an exception, or I can ignore the ClassCastException (do nothing in the catch block, as shown below).
    Which is better? Is it faster if I just omit the instance check and let cast() detect the errors? Is there a style convention here?Whatever you decide, just keep in mind that there is a semantic difference too:
    if(clazz.isInstance(t)) retval.add(clazz.cast(t));will only add instances of the requested class, whereas
    try { retval.add(clazz.cast(t)); } catch(ClassCastException e) {} will also add null values.

  • Help, try and catch and variables

    I have a private vector in one of my objects, i then add some items to it at the beginning of a method, the program then goes into a try/catch block where i add some more variables.
    However, the variables i add in the try/catch block only seem to exist within that block.
    In another method i refer to the vector again, but it only contains the elements i added before the try/catch block.
    Any suggestions?

    headers = new Vector();
    headers.add("String 1");
    headers.add("String 2");
    connect("database");
    System.out.println("Connected");
    try
    String mySQL = "SELECT * FROM " + table;
    Statement st = c.createStatement();
    System.out.println("Statement Created");
    st.executeQuery(mySQL);
    catch (Exception e)
    try
    StringTokenizer tk = new StringTokenizer(layoutString, "|");
    while (tk.hasMoreTokens())
    String tmpStr = tk.nextToken();
    if (tmpStr.equalsIgnoreCase("ScalePanel"))
    String tmp = tk.nextToken();
    headers.add(tmp);
    headers.add("number");
    else if (tmpStr.equalsIgnoreCase("OptionPanel"))
    String tmp = tk.nextToken();
    headers.add(tmp);
    headers.add("varchar(20)");
    else if (tmpStr.equalsIgnoreCase("InputPanel"))
    String tmp = tk.nextToken();
    headers.add(tmp);
    headers.add("varchar(20)");
    System.out.println("Table Doesn't Exist, creating...");
    String mySQL = "create table " + table + " (";
    for (int i = 0 ; i < headers.size() ; i++)
    if (i == 0)
    mySQL += headers.get(i) + " " + headers.get(++i);
    else
    mySQL += "," + headers.get(i) + " " + headers.get(++i);
    mySQL += ");";
    Statement st = c.createStatement();
    st.execute(mySQL);
    catch (Exception ex)
    System.out.println("Error while creating table");
    System.out.println(ex.getMessage());
    disconnect();
    I then refer to headers in another method, but it only contains the items before the try/catch.

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

  • 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) {
    }

  • Hi please advice on the keyword cleanup founc ina try and entry

    Hiii
                TRY .
                    lst_ykomv-kbetr = lv_ptemp2dp.
    *             Catching the exception in case the value is too big to be assign to kbetr
                  CATCH cx_sy_conversion_overflow INTO cxl_oref.
                    lv_text = cxl_oref->get_text( ).
                  CLEANUP.
                    CLEAR lst_ykomv-kbetr.
                ENDTRY.
    Please advise what is the purpose of a cleanup in a try and endtry block i read some documentation. but i don't really understand

    Searching help.sap.com might have helped you which you didn't.
    http://help.sap.com/saphelp_nw04/helpdata/en/a9/b8eef8fe9411d4b2ee0050dadfb92b/frameset.htm

  • 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

  • Throwing and catching deliberate errors in bash

    Hello,
    In many languages one can throw deliberate errors of a specific kind as well as catch-trap for specific errors. I'm having a hard time determining how to do this in bash 3.2 with it's 'trap' command.
    Moreover, I can't figure out whether or not if it's even possible to catch for specific thrown errors defined by a scripter in bash. My own tests have led to a dead end and I haven't come any better understanding from reading the bash info docs, and numerous online and in print examples of the 'trap' command.
    Basically, I wish to...
    1. First, have scripts throw a specifically, identifiable, unique error when a certain known bad state has been encountered that they can't handle.
    2. Secondly, to able to test for whether scripts are throwing an specific error under a certain condition.
    3. Trap for and catch only that specific error and then keep on going, performing further automated tests.
    Is this possible in bash?
    Below is an example which might better illustrate what I've attempted to do. It unfortunately, doesn't do what's needed at the moment. i.e.- It will catch all errors and exits but not a specific one.
    #--- The example below traps all errors but not the specific one.
    particular_function()
    current_status="some known bad condition"
    if [ "$current_status" = "some known bad condition" ]; then
    # Encountered some known condition we can't handle so throw specific error.
    echo "Encountered a, we knew this would happen, type error."
    exit -99
    fi
    testmethod_for_expectederror()
    trap 'echo "function threw expected error code as it should."' EXIT
    particular_function
    testmethod_for_expectederror
    echo "Continued passed caught error as desired and continuing further tests..."
    Thanks,
    -Anthony

    {quote:title=BobHarris wrote:}The bash trap statement was not intended as an alternate way to return errors.
    But if you want to generate your own signals, then use the kill command.
    See "man 1 kill". {quote}
    It sounds like I'm attempting to pound a square peg through a round hole? Attempting workarounds, like shaving off the corners of the peg, might eventually just lead to loss of sanity, time wasted - gone forever, never to return.
    So, perhaps I'll try some other method.
    If it offers a little more clarity, I'm trying determine [how to write tests|http://xp123.com/xplor/xp0101/index.shtml|Test-First Stoplight - write a test first before writing a line of code.], in bash, for situations where a script [should halt executing|http://xunitpatterns.com/Test%20Method.html#Expected%20Exception%20Te st|Expected exception test pattern] when it encounters something it can't handle rather than keep on going causing potential mishaps.
    Basically, I would like to avoid causing the [xUnit testing framework|http://www.martinfowler.com/bliki/Xunit.html|xUnit testing frameworks in XP] I'm using [(shUnit2)|http://code.google.com/p/shunit2/|shUnit2 project site] from incorrectly reporting expected errors, that are suppose to be thrown, by a script, as failures. An expected, [correctly thrown error|http://books.google.ca/books?id=gFgndevwMAC&pg=PA163&lpg=PA163&dq=%22exceptiontest%22+%22test+driven+development%22patterns&source=bl&ots=enHrtsSunH&sig=PbbvWbea_VkqVAbdGYZwJDUcygI&hl=en&ei=XQslS qzSDs-EmQfIvqCFCA&sa=X&oi=bookresult&ct=result&resnum=1|Catch expected exceptions and ignore them. in TDD by Kent Beck] should be counted as a success by the framework in that context. Assuming, the script didn't exit in a bad way. At the same time, unforeseen errors should not be blocked and should propagate up to be reported as an erring test.
    Thanks for your help,
    -Anthony

Maybe you are looking for