Help on "try block"

hi there
if the try block catches an exception, its catch block will execute, will the code return to the beginning of the try block or exit the try block and execute the next statement? if I use a try block to validate user input, will it keep trying until the input is valid, or I should use a loop. thank you .

When the code within the try block generates an
exception, the code in the catch block is executed and
then processing continues with the next statement
after the catch block.
Mark

Similar Messages

  • Parameters in try block..pls help

    I have the following code which I do not understand the reason it is not work. i.e. Putting the driver, dbURL, login, password value in the beginning work, however, setting it in the try blocks does not. Can you please help me? Thank you.
    public ConnectionManager()
    // (This block works OK if uncommented)
    //driver = "com.mysql.jdbc.Driver";
    //dbURL = "jdbc:mysql://localhost/BOOKINGSYSTEM";
    //login = "root";
    //password = "password";
    try {
    Properties Prop = new Properties();
    InputStream configStream = ConnectionManager.class.getClass().getResourceAsStream("/config/database.properties");
    Prop.load(configStream);
    configStream.close();
    //driver =Prop.getProperty("driver");
    //dbURL = Prop.getProperty("dbURL");
    //login = Prop.getProperty("login");
    //password = Prop.getProperty("password");
    // (This block DOES NOT works...why??)
    driver = "com.mysql.jdbc.Driver";
    dbURL = "jdbc:mysql://localhost/BOOKINGSYSTEM";
    login = "root";
    password = "password";
    } catch(IOException e) {
    System.out.println("Error: Cannot laod configuration file ");
    }

    I have the following code which I do not understand
    the reason it is not work. i.e. Putting the driver,
    dbURL, login, password value in the beginning work,
    however, setting it in the try blocks does not. Can
    you please help me? Thank you.What exactly do you mean by "it does not work"?

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

  • Oracle JSP Exception code too large for try block

    My jsp is exceeding the memory limit (64KB for Oracle 10g App server i think its the JVM limit),
    so it is throwing exception ,code too large for try block,how to over come this,I cant minimize the use of logic tags because it is business requirement.please help me out.

    I think you need to give a value to the attribute buffer in the <%@ page%> directive to solve the problem.
    There will not be any need of going for pagination then.
    buffer="none | 8kb | sizekb"The buffer size in kilobytes used by the out object to handle output sent from the compiled JSP page to the client Web browser. The default value is 8kb. If you specify a buffer size, the output is buffered with at least the size you specified.
    check the documentation at
    http://java.sun.com/products/jsp/tags/11/syntaxref11.fm7.html
    Uday

  • Can't throw exception inside try block!

    Hi,
    I'm having a problem trying to throw an error inside a try block.
    To illustrate:
    public class TestException {
    public TestException() {
    try {
    int ret = foo();
    System.out.println("ret is " + ret);
    } catch (Exception ex) {
    System.out.println("exception caught");
    public int foo() throws Exception {
    int ret = 0;
    try {
    throw new Exception("test exception");
    } finally {
    return ret;
    public static void main(String[] args) {
    new TestException();
    If I run this the only output is "ret is 0" - I do not catch the thrown exception! What am I doing wrong?
    Any and all help will be very gratefully received.
    Thanks.

    I need to correct myself: I've re-read the spec, and actually the behaviour is conformant with the JLS: JLS says that the return statement completes abruptly, and an abrupt return in a finally block that didn't have a (applicable or any) catch block will result in the original exception being 'forgotten'.
    Very unintuitive, but as-spec'ed

  • Posiibility for terminating jvm inside try block so that finally block wont

    posiibility for terminating jvm inside try block so that finally block wont execute at all ?
    But in that case what will happen?
    Is it safe for any practical situation ?
    Threads: t.stop()
    JVM : System.exit()
    which one can really help and where?

    What if security Manager comes into picture?
    class ExitCatchingSecurityManager extends SecurityManager
    public void checkExit(int status)
    Process.terminateProcessWithThreadGroup(getThreadGroup());
    throw new SecurityException();
    What if an application calls System.exit()?
    We still have one big hole in our multiprocess library. If any application calls System.exit(), the JVM terminates, and all the pseudo-processes will be destroyed with no warning. Fortunately, Java's design once again comes to our aid. Any call to System.exit() is first checked by the SecurityManager to see if the application has permission to terminate the JVM. We can install our own SecurityManager to catch the System.exit() call, disallow it, and terminate the pseudo-process instead. The SecurityManager is actually quite simple to define:
    class ExitCatchingSecurityManager extends SecurityManager
    public void checkExit(int status)
    Process.terminateProcessWithThreadGroup(getThreadGroup());
    throw new SecurityException();
    In addition, the SecurityManager should define all other checks so that they do not block pseudo-processes from running. A simple null call for all check* methods will work. We install our own SecurityManager by calling System.setSecurityManager(), i.e., by adding the following line near the startup of the multiprocess library:
    System.setSecurityManager(new ExitCatchingSecurityManager());
    The Process.terminateProcessWithThreadGroup() method is simple to define, by holding a collection of Process objects in the Process class, searching the collection to find the Process with the identical ThreadGroup, then terminating that Process.

  • Does anyone know something about a promorewards.prizeswood.eu pop up box (suppose a virus) on chromium? please help everything is blocked on my macbook air

    does anyone know something about a promorewards.prizeswood.eu pop up box (suppose a virus) on chromium? please help everything is blocked on my macbook air

    This may be due to adware called GoPhoto.it, which there was a sudden increase in reports about last week. Try the removal instructions here:
    http://www.thesafemac.com/arg-gophotoit/
    If you don't find any parts of GoPhoto.it installed, try going through my Adware Removal Guide from the beginning.

  • Try End Try Block

    Dear All,
      I need some help in Try/End Try block. My requirement is that I need to check out of 3 FM's which exists in the system and depending on the FM which exists I need to set a particular flag and call that FM.
      So can I try some algorithm like this.
    TRY
      CALL FM1
      Set flag1
    TRY
      CALL FM2
      Set flag2
    CATCH
      CALL FM3
      Set flag3
    Please let me know, it would be of great help.
    Thanks & Warm Regards, Vinay

    The other party is not informed they are blocked.  Calls go straight to voicemail..  Messages just never appear on your phone. 

  • To all of my friends in fb: please help me in blocking my stolen Ipad3 SN: DY******VD1 thanks so much, I would greatly appreciate if culprit would learn his lesson!

    To all of my friends in fb: please help me in blocking my stolen Ipad3 SN: DY*****VD1 thanks so much, I would greatly appreciate if culprit would learn his lesson!
    <Edited by Host>

    Apple does not track nor block iPads. If it was equipped to access
    cellular, report it to your cellular provider. Report the loss to your
    local police. If covered by your insurance, report to your insurance
    company.
    Immediately change all of your passwords.
    If you had previously set it up, you may be able to track it via
    Find my iPhone.
    Texas Mac Man has some excellent links in this thread:
    https://discussions.apple.com/thread/4869627?tstart=270
    Message was edited by: imobl added link to Texas Mac Man post

  • Is it possible to get back to the Try block from a Catch block?

    I would like to perform validations on a config file. To do so, I have a method which will throw a MissingConfigException or an InvalidConfigException if something is missing or if something doesn't match a regex pattern. Although I have to do that with many different configs and I would like to go through all of them so that my error message will report all missing / incorrect configs at once instead of 1 at a time. Thus, I wanted to know if there would be any way I could do something like:
    try {
         config.validate("ServerPort","\\d+");
         config.validate("MaxClients","\\d+");
    } catch(MissingConfigException e) {
    } catch(InvalidConfigException e) {
    and have the catch block executed before going through the try block from where the exception was thrown.
    Thanks in advance!                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    No, you can't jump back into the try. You can put your try/catch inside a loop though, so that if one fails, it will loop around and start a new try for the next one. Define a class that holds all the data you need to pass to validate, and make an array or List of those objects. Change or add a validate signature that takes this object, or just extract the strings from each one when you call validate.
    ThingToValidate[] val = new ThingToValidate[] { new ThingToValidate("ServerPort", "\\d+"),
        new ThingToValidate("MaxClients", "\\d+"),
    for (int ix = 0; ix < val.length; ix++) {
        try {
            config.validate(val[ix]);
            // OR
            config.validate(val[ix].getThingy, val[ix].getOtherThingy[]);
        catch (....) {
            // logger.warn("failed...");

  • I just updated my iphone to IOS 7 and cannot get my imessage to work, it keeps saying "waiting for activation" nothing i have read online has helped me try to fix the problem. why is it doing this and how can i fix it?

    I just updated my iphone to IOS 7 and cannot get my imessage to work, it keeps saying "waiting for activation" nothing i have read online has helped me try to fix the problem. why is it doing this and how can i fix it?

    Here's a good troubleshooting article about imessage "waiting for activation".
    http://support.apple.com/kb/TS4268

  • Handling socket exception - Retrying a "try" block

    I have a program which attempts to retrieve an object through a socket. However sometimes I get the following exception:
    java.net.SocketException: Connection reset
    This is a problem as I need the object to continue program execution.
    An overview of the code is:
    try {
                UrlServerObject crawlUrlObj = getUrlToCrawl();
                // Download webpage at the url returned by getUrlToCrawl()
                webpage = loadPage(crawlUrlObj);
    catch(java.net.SocketException ex) {
              System.err.println("An exception occurred.\n" +
                        "The exception was: " + ex.toString());
            }The getUrlToCrawl() method simply opens a socket a communicates with a server which sends back an object.
    My question is what is the best way to catch the exception and "retry" the complete "try" block until an object is read?
    Thanks

    When you say a loop, do you mean something along the
    lines of:
    boolean gotUrl = false;
    while(!gotUrl) {
    UrlServerObject crawlUrlObj = getUrlToCrawl();
    if(crawlUrlObj != null) gotUrl = true;
    }The exception would be thrown in the catch block
    still though?getUrlToCrawl is presumably the code you originally posted? Yep, that's about the size of it. Although I wouldn't keep trying until you got a URL, you should consider the possibility that there isn't one, and deal with that. I'd try it a set number of times, and move on after that

  • Return statement inside try block

    what is wrong if i write code like as below...please explain me since i am new to java
    class sample{
    public String method(){
    try{
    String str="abc";
    return abc;
    catch(Exception e){}
    }

    veldhanas wrote:
    return abc;In your code there is no varible declared as abc. It is a value assigned in str.
    Suppose if the code in try statement throws exception the return statement is skipped and the
    associated catch block will get executed. So your catch block must return a result of type String.... or throw another (or the same) exception.
    In this case, since there's no way the code in the given "try" block can throw an exception, it would have been better to not even have a try/catch block in the first place.
    And almost never just swallow exceptions like that (an empty catch block). There are only a few cases where it's ok to swallow them (such as in finally blocks where you're cleaning up resources which may throw exceptions while cleaning up, and you want to continue cleaning up and ignore those kinds of exceptions).

  • HT4759 last friday my iphone 5 hold up of two people plss help me to block my phone so they cant use my iphone plss help me apple.. i have a serial number of my iphone 5 i bought imy iphone in japan.. and iit is not open line here.. only wifi it can used.

    last friday night my iphone5 hold up with two bud guys.. how can i block it so they connot used anymore my phone plss help me apple..i have a serial number here ti keep it so i thonk it can used i bought my iphone in japan..  THIS ISMY SERIAL NUMBER HELP ME PLSS APPLE ( serial nu.F1*****TWG ) iphone 5 32GB plss help me to block it right now.. godbless..
    <edited by host>

    Hello Renvin29,
    It sounds like you need to disable your iPhone remotely. I'm sorry to hear about your phone! The only way to do this with is Apple services is if you had Find my iPhone enabled. You have 2 options:
    You can use this article to put the phone into Lost Mode and preserve your data on it, but prevent access to it:
    iCloud: Use Lost Mode
    http://support.apple.com/kb/PH2700
    Or you can just erase it remotely outright:
    iCloud: Erase your device
    http://support.apple.com/kb/PH2701
    You should also take a look at this article for additional info on what to do about this situation:
    If your iPhone, iPad, or iPod touch is lost or stolen
    http://support.apple.com/kb/HT5668
    Thank you for using Apple Support Communities.
    Take care,
    Sterling

  • Won't recognise code in try block

    I've got a try block which has a line of code in it as shown:
         public static String ProcessUserInput(){          
              BufferedReader kbd = new BufferedReader(new InputStreamReader(System.in));
              try{
         String line = kbd.readLine();
    catch (IOException ex)
    System.out.println( "Error reading keyboard input." );
    return line;
    When i compile this it gives me this error:
    cannot resolve symbol
    symbol : variable line
    location: class UserException
    return line;
    It seem like it does not recognise what is in the try block why is this.

    A variable's scope--the piece of your code where it's visible--is the nearest enclosing block. In this case, line is only visible in the try block.
    String line = null;
    try {
        line = kbe.readLine();
    catch (...) {
    return line;Side note: Just printing an error message is NOT the way to handle exceptions. First, it lets subsequent code continue executing as if everything's fine--you've taken away its way of knowing that things are NOT fine. You should either actually handle the exception (by providing some default behavior, or retrying), or else just let it be thrown, or wrap it and rethrow it.

Maybe you are looking for